在iOS 10之前,自定义相机一般使用AVCaptureStillImageOutput实现。但是AVCaptureStillImageOutput在iOS 10以后被弃用了。
所以我们来使用AVCapturePhotoOutput来实现自定义简单相机,AVCapturePhotoOutput 的功能自然会更加强大,不仅支持简单JPEG图片拍摄,还支持Live照片和RAW格式拍摄。
使用:
首先初始化:按照需要参数初始化就行了,和AVCaptureStillImageOutput差别不大。直接上代码:
self.session = [AVCaptureSession new];
[self.session setSessionPreset:AVCaptureSessionPresetHigh];
NSArray *devices = [NSArray new];
devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices) {
if (isBack) {
if ([device position] == AVCaptureDevicePositionBack) {
_device = device;
break;
}
}else {
if ([device position] == AVCaptureDevicePositionFront) {
_device = device;
break;
}
}
}
NSError *error;
self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:&error];
if ([self.session canAddInput:self.input]) {
[self.session addInput:self.input];
}
self.imageOutput = [[AVCapturePhotoOutput alloc] init];
NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecJPEG};
_outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
[self.imageOutput setPhotoSettingsForSceneMonitoring:_outputSettings];
[self.session addOutput:self.imageOutput];
self.preview = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
[self.preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[self.preview setFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
[self.layer addSublayer:self.preview];
[self.session startRunning];
实现照片获取:
AVCaptureStillImageOutput中使用captureStillImageAsynchronouslyFromConnection 在bolck中直接可以获取到图片,AVCapturePhotoOutput需要实现AVCapturePhotoCaptureDelegate协议,在协议中获取。
获取当前屏幕图片输出:
[self.imageOutput capturePhotoWithSettings:_outputSettings delegate:self];
实现AVCapturePhotoCaptureDelegate协议,并在didFinishProcessingPhotoSampleBuffer方法中获取图片:
- (void)captureOutput:(AVCapturePhotoOutput *)captureOutput didFinishProcessingPhotoSampleBuffer:(nullable CMSampleBufferRef)photoSampleBuffer previewPhotoSampleBuffer:(nullable CMSampleBufferRef)previewPhotoSampleBuffer resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings bracketSettings:(nullable AVCaptureBracketedStillImageSettings *)bracketSettings error:(nullable NSError *)error {
NSData *data = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];
UIImage *image = [UIImage imageWithData:data];
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
这样就获取到图片了。
最后附Demo