ios AVFoundation tap to focus
avfoundation, camera, ios
Solution
You have to adjust the touchPoint to a range of [0,1] using something like the following code:
CGRect screenRect = [[UIScreen mainScreen] bounds];
screenWidth = screenRect.size.width;
screenHeight = screenRect.size.height;
double focus_x = thisFocusPoint.center.x/screenWidth;
double focus_y = thisFocusPoint.center.y/screenHeight;
[[self captureManager].videoDevice lockForConfiguration:&error];
[[self captureManager].videoDevice setFocusPointOfInterest:CGPointMake(focus_x,focus_y)];
[[self captureManager].videoDevice unlockForConfiguration];
The documentation on this can be found in Apple - AV Foundation Programming Guidelines - see section Media Capture where you will find information on Focus Modes:
If it’s supported, you set the focal point using focusPointOfInterest. You pass a CGPoint where {0,0} represents the top left of the picture area, and {1,1} represents the bottom right in landscape mode with the home button on the right—this applies even if the device is in portrait mode.
Problem
I am trying to create a camera app which, would act like the default camera app more or less. The thing, which is not working for me at the moment, is tap to focus. I want the camera to focus and do whatever it does on my touched point, just like the real camera app does. Here's my viewDidLoad ``` - (void)viewDidLoad { [super viewDidLoad]; // Session _session = [[AVCaptureSession alloc] init]; _session.sessionPreset = AVCaptureSessionPresetPhoto; // Input _videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; _videoInput = [AVCaptureDeviceInput deviceInputWithDevice:_videoDevice error:nil]; // Output _frameOutput = [[AVCaptureVideoDataOutput alloc] init]; _frameOutput.videoSettings = [NSDictionary dictionaryWithObject:AVVideoCodecJPEG forKey:AVVideoCodecKey]; [_frameOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()]; [_session addInput:_videoInput]; [_session addOutput:_frameOutput]; [_session startRunning]; }; ``` And here's the method that should make my camera focus stuff on click. ``` -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [touches enumerateObjectsUsingBlock:^(id obj, BOOL *stop) { UITouch *touch = obj; CGPoint touchPoint = [touch locationInView:touch.view]; focusLayer.frame = CGRectMake((touchPoint.x-25), (touchPoint.y-25), 50, 50); if ([_videoDevice isFocusPointOfInterestSupported]) { NSError *error; if ([_videoDevice lockForConfiguration:&error]) { [_videoDevice setFocusPointOfInterest:touchPoint]; [_videoDevice setExposurePointOfInterest:touchPoint]; [_videoDevice setFocusMode:AVCaptureFocusModeAutoFocus]; if ([_videoDevice isExposureModeSupported:AVCaptureExposureModeAutoExpose]){ [_videoDevice setExposureMode:AVCaptureExposureModeAutoExpose]; } [_videoDevice unlockForConfiguration]; } } // NSLog(@"x = %f, y = %f", touchPoint.x, touchPoint.y); }]; } ``` Nothing really happens once I click on the screen.