相信大家开发自定义相机的时候都有碰到过 相机怎么自定对焦。 百度查找到的一般都是检查照片的模糊度。其实不用这么麻烦苹果有自带的方法。
不多说附上代码
/**
* AVCaptureSession对象来执行输入设备和输出设备之间的数据传递
*/
@property (nonatomic,strong)AVCaptureSession* session;
@property (nonatomic,strong)AVCaptureDevice *device;
这个2个是开发相机的必备的
self.session = [[AVCaptureSessionalloc]init];
if ([self.sessioncanSetSessionPreset:AVCaptureSessionPresetPhoto])
{
self.session.sessionPreset = AVCaptureSessionPresetPhoto;
}
NSError *error;
self.device = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];
//更改这个设置的时候必须先锁定设备,修改完后再解锁,否则崩溃
[self.devicelockForConfiguration:nil];
//设置闪光灯为自动
[self.devicesetFlashMode:AVCaptureFlashModeAuto];
[_sessionbeginConfiguration];
if ([_deviceisWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
[_devicesetWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
}
[self.deviceunlockForConfiguration];
[_sessioncommitConfiguration];
self.videoInput = [[AVCaptureDeviceInputalloc]initWithDevice:self.deviceerror:&error];
if (error) {
NSLog(@"%@",error);
}
self.stillImageOutput = [[AVCaptureStillImageOutputalloc]init];
//输出设置。AVVideoCodecJPEG 输出jpeg格式图片
NSDictionary * outputSettings = [[NSDictionaryalloc]initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey,nil];
[self.stillImageOutputsetOutputSettings:outputSettings];
// 这里就是监听相机自动对焦的
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(subjectAreaDidChange:)name:AVCaptureDeviceSubjectAreaDidChangeNotificationobject:self.device];
if ([self.sessioncanAddInput:self.videoInput]) {
[self.sessionaddInput:self.videoInput];
}
if ([self.sessioncanAddOutput:self.stillImageOutput]) {
[self.sessionaddOutput:self.stillImageOutput];
}
//初始化预览图层
self.previewLayer = [[AVCaptureVideoPreviewLayeralloc]initWithSession:self.session];
[self.previewLayersetVideoGravity:AVLayerVideoGravityResize];
[self.previewLayersetFrame:CGRectMake(0,0,self.frame.size.width,self.frame.size.height)];
- (void)subjectAreaDidChange:(NSNotification *)notification
{
//先进行判断是否支持控制对焦
if (_device.isFocusPointOfInterestSupported &&[_deviceisFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
NSError *error =nil;
//对cameraDevice进行操作前,需要先锁定,防止其他线程访问,
[_devicelockForConfiguration:&error];
[_devicesetFocusMode:AVCaptureFocusModeAutoFocus];
[selffocusAtPoint:self.center];
//操作完成后,记得进行unlock。
[_deviceunlockForConfiguration];
}
}
完了记得移除监听。