引言
最近的项目,系统的相机无法满足需求,这个时候就需要自定义相机了。
1.先把UI搭建好
拍照界面主要是相机的预览层以及拍完后照片的显示。这里是在初始化操作之后做的。
self.device = [self cameraWithPosition:AVCaptureDevicePositionBack];
self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil];
self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
self.session = [[AVCaptureSession alloc] init];
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
2.自定义相机
自定义相机实现拍照、前后摄像头的切换、闪光灯、聚焦、放大缩小、拍照后预览、重拍等功能。
2.1 初始化操作
AVCaptureDevice
AVCaptureDeviceInput
AVCaptureStillImageOutput
AVCaptureSession
AVCaptureVideoPreviewLayer
AVCaptureConnection
2.1.1AVCaptureDevice
用来获取相机设备的一些属性,实现摄像头和麦克风的初始化操作. 闪光灯、手电筒、聚焦、曝光、白平衡等一些基本设置.这里我没有做对权限的控制,在实际的开发中是要做的.当用户点击不允许使用相机的时候,如果不做处理的话,就会显示黑屏甚至闪退.做权限处理,引导用户去设置页面打开摄像头权限。
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for ( AVCaptureDevice *device in devices )
if ( device.position == position ){
return device;
}
return nil;
}
2.1.2 AVCaptureDeviceInput
设置Session的输入源。可以是Video,也可以是Audio,或者两者都添加。
if ([self.session canAddInput:self.input]) {
[self.session addInput:self.input];
}
2.1.3 AVCaptureStillImageOutput
设置Session的输出源。可以是图片源、音视频源、文件源等.这里用相机拍照,当然输出的是AVCaptureStillImageOutput图片源.AVCaptureStillImageOutput在iOS10中已经被AVCapturePhotoOutput所代替。
if ([self.session canAddOutput:self.imageOutput]) {
[self.session addOutput:self.imageOutput];
}
2.1.4 AVCaptureSession
设置输出的画质。要判断是iPad还是iphone。sessionPreset是一个枚举,您可以点击进去看一下,结合实际项目中的需要进行选择。另外,值得注意的是:如果您设置的画质高于手机本身支持的分辨率的话那么会造成崩溃。比如,我现在设置的是 AVCaptureSessionPresetiFrame960x540大概需要摄像头支持50W的像素,而iphone4S的前置摄像头只有30W的像素,显然达不到标准。
2.1.5 AVCaptureVideoPreviewLayer
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
//拿到的图像的大小可以自行设定
self.session.sessionPreset = AVCaptureSessionPreset640x480;
//输入输出设备结合
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, kScreenWidth, kScreenHeight);
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:self.previewLayer];
2.2 实现拍照功能
//拍照功能
- (void)photoBtnDidClick:(UIButton *)sender
{
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];
// self.image = [UIImage imageWithData:imageData];
[self.session stopRunning];
}];
}
这里的AVCaptureConnection是session和AVCaptureStillImageOutput连接的枢纽。通过回调拿到图片的数据,显示出来。这样就完成了基本的拍照功能。但如果把拍好的照片传给后台,会发现照片旋转了90度,明明在手机上是竖屏的,后台下载后却是横屏的。这是由于iphone的方向传感器造成的,遇到这种问题,只需要调整一下UIImage的imageOrientation属性即可。这个网上有现成的demo。如果您有兴趣,这篇文章我觉得写的非常细致。如何处理iOS中照片的方向,您可以参考。在这个基础上,再实现前置摄像头拍照。旋转摄像头的时候,可以再加一个翻转动画,当然这根据需求而定。
- (void)rotateCamera
{
NSArray *inputs = self.session.inputs;
for (AVCaptureDeviceInput *input in inputs ) {
AVCaptureDevice *device = input.device;
if ([device hasMediaType:AVMediaTypeVideo] ) {
AVCaptureDevicePosition position = device.position;
AVCaptureDevice *newCamera = nil;
AVCaptureDeviceInput *newInput = nil;
if(position == AVCaptureDevicePositionFront)
newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
else
newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
[self.session beginConfiguration];
[self.session removeInput:input];
[self.session addInput:newInput];
[self.session commitConfiguration];
break;
}
}
}
2.3 辅助功能
2.3.1 对焦、闪光灯
在预览层上加一层遮照View来响应手势的触发。聚焦功能如下。
//AVCaptureFlashMode 闪光灯
//AVCaptureFocusMode 对焦
//AVCaptureExposureMode 曝光
//AVCaptureWhiteBalanceMode 白平衡
//闪光灯和白平衡可以在生成相机时候设置
//曝光要根据对焦点的光线状况而决定,所以和对焦一块写
//point为点击的位置
- (void)focusAtPoint:(CGPoint)point{
CGSize size = self.view.bounds.size;
CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
NSError *error;
if ([self.device lockForConfiguration:&error]) {
//对焦模式和对焦点
if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
[self.device setFocusPointOfInterest:focusPoint];
[self.device setFocusMode:AVCaptureFocusModeAutoFocus];
}
//曝光模式和曝光点
if ([self.device isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) {
[self.device setExposurePointOfInterest:focusPoint];
[self.device setExposureMode:AVCaptureExposureModeAutoExpose];
}
[self.device unlockForConfiguration];
//设置对焦动画
// _focusView.center = point;
// _focusView.hidden = NO;
// [UIView animateWithDuration:0.3 animations:^{
// _focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
// }completion:^(BOOL finished) {
// [UIView animateWithDuration:0.5 animations:^{
// _focusView.transform = CGAffineTransformIdentity;
// } completion:^(BOOL finished) {
// _focusView.hidden = YES;
// }];
// }];
}
}
3.总结
以上,基本的相机功能就实现了。我参照别人的文档重新整理的代码,下面是我的全部实现的代码,有部分没有使用的方法。
//
// CJHCameraVC.m
// cjh
//
// Created by 阿杰 on 2019/12/3.
// Copyright © 2019 njcjh. All rights reserved.
//
#import "CJHCameraVC.h"
#import
@interface CJHCameraVC ()
@property (nonatomic, strong) AVCaptureDevice *device;//捕获设备,通常是前置摄像头,后置摄像头,麦克风(音频输入)
@property (nonatomic, strong) AVCaptureDeviceInput *input;//代表输入设备,他使用AVCaptureDevice 来初始化
@property (nonatomic ,strong) AVCaptureStillImageOutput *imageOutput;//输出图片
@property (nonatomic, strong) AVCaptureSession *session;//由他把输入输出结合在一起,并开始启动捕获设备(摄像头)
@property (nonatomic ,strong) AVCaptureVideoPreviewLayer *previewLayer;//图像预览层,实时显示捕获的图像
@property (nonatomic,strong) UIImageView *bottomImageView;
@property (nonatomic, strong) UIButton *backBtn;//返回按钮
@property (nonatomic,strong) UIButton *photoBtn;
@end
@implementation CJHCameraVC
- (void)viewDidLoad {
[super viewDidLoad];
[self cameraDistrict];
}
-(void) viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
//[MainTabBarController selectIndex:1];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark --- mySelf
- (void)cameraDistrict
{
// AVCaptureDevicePositionBack 后置摄像头
// AVCaptureDevicePositionFront 前置摄像头
self.device = [self cameraWithPosition:AVCaptureDevicePositionBack];
self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil];
self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
self.session = [[AVCaptureSession alloc] init];
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
// 拿到的图像的大小可以自行设定
// AVCaptureSessionPreset320x240
// AVCaptureSessionPreset352x288
// AVCaptureSessionPreset640x480
// AVCaptureSessionPreset960x540
// AVCaptureSessionPreset1280x720
// AVCaptureSessionPreset1920x1080
// AVCaptureSessionPreset3840x2160
self.session.sessionPreset = AVCaptureSessionPreset640x480;
//输入输出设备结合
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, kScreenWidth, kScreenHeight);
self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:self.previewLayer];
//设备取景开始
[self.session startRunning];
if ([_device lockForConfiguration:nil]) {
//自动闪光灯,
if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
[_device setFlashMode:AVCaptureFlashModeAuto];
}
//自动白平衡,但是好像一直都进不去
if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
[_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
}
[_device unlockForConfiguration];
}
//返回
[self.backBtn setBackgroundImage:[UIImage imageNamed:@"default_back_3"] forState:UIControlStateNormal];
//底部图片
[self.bottomImageView setImage:[UIImage imageNamed:@"jifu_bottomTitle"]];
//拍照按钮
[self.photoBtn setBackgroundImage:[UIImage imageNamed:@"jifu_camera"] forState:UIControlStateNormal];
}
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for ( AVCaptureDevice *device in devices )
if ( device.position == position ){
return device;
}
return nil;
}
//拍照功能
- (void)photoBtnDidClick:(UIButton *)sender
{
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];
// self.image = [UIImage imageWithData:imageData];
[self.session stopRunning];
}];
}
#pragma - 保存至相册
- (void)saveImageToPhotoAlbum:(UIImage*)savedImage
{
UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
// 指定回调方法
- (void)image:(UIImage *)image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
NSString *msg = nil ;
if(error != NULL){
msg = @"保存图片失败" ;
}else{
msg = @"保存图片成功" ;
}
// [MBProgressHUD showError:msg toView:self.view];
}
//设置前后相机
- (void)changeCamera{
NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
if (cameraCount > 1) {
NSError *error;
//给摄像头的切换添加翻转动画
CATransition *animation = [CATransition animation];
animation.duration = .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];
animation.subtype = kCATransitionFromLeft;//动画翻转方向}
}else {
newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
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(@"toggle carema failed, error = %@", error);
}
}
}
//AVCaptureFlashMode 闪光灯
//AVCaptureFocusMode 对焦
//AVCaptureExposureMode 曝光
//AVCaptureWhiteBalanceMode 白平衡
//闪光灯和白平衡可以在生成相机时候设置
//曝光要根据对焦点的光线状况而决定,所以和对焦一块写
//point为点击的位置
- (void)focusAtPoint:(CGPoint)point{
CGSize size = self.view.bounds.size;
CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
NSError *error;
if ([self.device lockForConfiguration:&error]) {
//对焦模式和对焦点
if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
[self.device setFocusPointOfInterest:focusPoint];
[self.device setFocusMode:AVCaptureFocusModeAutoFocus];
}
//曝光模式和曝光点
if ([self.device isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) {
[self.device setExposurePointOfInterest:focusPoint];
[self.device setExposureMode:AVCaptureExposureModeAutoExpose];
}
[self.device unlockForConfiguration];
//设置对焦动画
// _focusView.center = point;
// _focusView.hidden = NO;
// [UIView animateWithDuration:0.3 animations:^{
// _focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
// }completion:^(BOOL finished) {
// [UIView animateWithDuration:0.5 animations:^{
// _focusView.transform = CGAffineTransformIdentity;
// } completion:^(BOOL finished) {
// _focusView.hidden = YES;
// }];
// }];
}
}
#pragma mark - 返回
-(void)backAction:(UIButton *)sender
{
[self dismissViewControllerAnimated:YES completion:^{
}];
}
#pragma mark -- 初始化对象
-(UIButton *)backBtn{
if(!_backBtn){
_backBtn = [[UIButton alloc] init];
[self.view addSubview:_backBtn];
[_backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(30);
make.left.mas_equalTo(20);
make.size.mas_equalTo(CGSizeMake(22, 22));
}];
[_backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
}
return _backBtn;
}
-(UIImageView *)bottomImageView
{
if (!_bottomImageView) {
_bottomImageView = [[UIImageView alloc] init];
_bottomImageView.contentMode = UIViewContentModeScaleAspectFit;
[self.view addSubview:_bottomImageView];
MJWeakSelf;
[_bottomImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.bottom.mas_equalTo(weakSelf.view.bottom).offset(-28);
make.right.mas_equalTo(weakSelf.view).offset(-10);
make.left.mas_equalTo(weakSelf.view).offset(10);
make.height.mas_equalTo(106);
}];
}
return _bottomImageView;
}
-(UIButton *)photoBtn{
if(!_photoBtn){
_photoBtn = [[UIButton alloc] init];
[self.view addSubview:_photoBtn];
MJWeakSelf;
[_photoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerX.mas_equalTo(weakSelf.view);
make.bottom.mas_equalTo(weakSelf.bottomImageView.mas_top).offset(-4);
make.size.mas_equalTo(CGSizeMake(83, 83));
}];
[_photoBtn addTarget:self action:@selector(photoBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
}
return _photoBtn;
}
@end
参考:https://www.jianshu.com/p/dfee61a3d5a1
参考:https://blog.csdn.net/TaLinBoy/article/details/84138408
参考:https://www.jianshu.com/p/9809760654ea