第一步,先导入#import <AVFoundation/AVFoundation.h>
第二步,创建需要的对象
@property (nonatomic,strong) AVCaptureDevice *devides;
@property (nonatomic,strong) AVCaptureDeviceInput *input;//输入设备
@property (nonatomic,strong) AVCaptureStillImageOutput *imageOutput;//输出图片
@property (nonatomic,strong) AVCaptureSession *session;//会话
@property (nonatomic,strong) AVCaptureVideoPreviewLayer *previewLayer;//预览层
第三部,UI设置
- (void)initCamera
{
self.devides = [self cameraWithPosition:AVCaptureDevicePositionBack];
self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.devides error:nil];
self.imageOutput = [[AVCaptureStillImageOutput alloc]init];
self.session = [[AVCaptureSession alloc]init];
self.session.sessionPreset = AVCaptureSessionPreset1280x720;
if ([self.session canAddInput:self.input])
{
[self.session addInput:self.input];
}
if ([self.session canAddOutput:self.imageOutput])
{
[self.session addOutput:self.imageOutput];
}
/**输出预览层**/
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
self.previewLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:self.previewLayer];
[self.session startRunning];
/**在这里添加需要的图层,比如人脸识别时需要的脸型图层**/
CALayer *faceRectLayer = [CALayer new];
faceRectLayer.zPosition = 1;
faceRectLayer.frame = CGRectMake(0, 0, WIDTH, HEIGHT );
faceRectLayer.backgroundColor = [UIColor colorWithRed:200/255 green:200/255 blue:200/255 alpha:0].CGColor;
faceRectLayer.contents = (__bridge id _Nullable)(self.previewImage.CGImage);
[self.previewLayer addSublayer:faceRectLayer];
/**切换前后相机**/
change = [UIButton buttonWithType:UIButtonTypeCustom];
change.frame = CGRectMake(0, 0, 40, 40);
change.center = CGPointMake(WIDTH - 60, HEIGHT - 60);
[change setBackgroundImage:[UIImage imageNamed:@"切换"] forState:UIControlStateNormal];
[change addTarget:self action:@selector(changeCamera) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:change];
/**拍照**/
takePhoto = [UIButton buttonWithType:UIButtonTypeCustom];
takePhoto.frame = CGRectMake(0, 0, 60, 60);
takePhoto.center = CGPointMake(WIDTH/2, HEIGHT - 60);
[takePhoto setBackgroundImage:[UIImage imageNamed:@"拍照"] forState:UIControlStateNormal];
[takePhoto addTarget:self action:@selector(selectedToTakePhoto) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:takePhoto];
/**返回**/
backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
backBtn.frame = CGRectMake(0, 0, 40, 40);
backBtn.center = CGPointMake(60, HEIGHT - 60);
[backBtn setBackgroundImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
[backBtn addTarget:self action:@selector(selectedToDismiss) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:backBtn];
}
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for ( AVCaptureDevice *device in devices )
if ( device.position == position )
{
return device;
}
return nil;
}
第四步,切换前后相机
#pragma mark 切换前后相机
- (void)changeCamera
{
NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
if (cameraCount > 1)
{
NSError *error;
/**添加切换时的翻转动画**/
CATransition *animation = [CATransition animation];
animation.duration = 0.5f;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.type = @"oglFlip";
AVCaptureDevice *newCamera = nil;
AVCaptureDeviceInput *newInput = nil;
/**获取另外一个摄像头的位置**/
AVCaptureDevicePosition position = [[_input device] position];
if (position == AVCaptureDevicePositionFront)
{
newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
self.session.sessionPreset = AVCaptureSessionPreset1280x720;
animation.subtype = kCATransitionFromLeft;//动画翻转方向
}
else
{
newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
self.session.sessionPreset = AVCaptureSessionPreset1280x720;
animation.subtype = kCATransitionFromRight;//动画翻转方向
}
/**生成新的输入**/
newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
[self.previewLayer addAnimation:animation forKey:nil];
if (newInput != nil)
{
[self.session beginConfiguration];
[self.session removeInput:self.input];
if ([self.session canAddInput:newInput])
{
[self.session addInput:newInput];
self.input = newInput;
}
else
{
[self.session addInput:self.input];
}
[self.session commitConfiguration];
}
else if (error)
{
NSLog(@"Change carema failed.Error:%@", error);
}
}
}
第五步,拍照,获取image
#pragma mark 拍照
- (void)selectedToTakePhoto
{
AVCaptureConnection *conntion = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
if (!conntion)
{
NSLog(@"拍照失败!");
return;
}
[self.imageOutput captureStillImageAsynchronouslyFromConnection:conntion completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
{
if (imageDataSampleBuffer == nil)
{
return ;
}
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [UIImage imageWithData:imageData];
if (image == nil)
{
return;
}
/**block监听拍照动作,获取image**/
self.takePhotoImage(image);
}];
}