导入相机的API在AVFoundation里所以得包含头文件#import <AVFoundation/>
1.
自定义相机需要的属性
@interface CustomCameraVC ()<UIAlertViewDelegate>
//捕获设备,通常是前置摄像头,后置摄像头,麦克风(音频输入)
@property(nonatomic)AVCaptureDevice *device;
//AVCaptureDeviceInput 代表输入设备,他使用AVCaptureDevice 来初始化
@property(nonatomic)AVCaptureDeviceInput *input;
//当启动摄像头开始捕获输入
@property(nonatomic)AVCaptureMetadataOutput *output;
//照片输出流
@property (nonatomic)AVCapturePhotoOutput *ImageOutPut;
//session:由他把输入输出结合在一起,并开始启动捕获设备(摄像头)
@property(nonatomic)AVCaptureSession *session;
//图像预览层,实时显示捕获的图像
@property(nonatomic)AVCaptureVideoPreviewLayer *previewLayer;
// ------------- UI --------------
//拍照按钮
@property (nonatomic)UIButton *photoButton;
//闪光灯按钮
@property (nonatomic)UIButton *flashButton;
//聚焦
@property (nonatomic)UIView *focusView;
//是否开启闪光灯
@property (nonatomic)BOOL isflashOn;
@end
2.判断相机权限
#pragma mark- 检测相机权限,自动跳到设置里。
- (BOOL)checkCameraPermission
{
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (authStatus == AVAuthorizationStatusDenied) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"请打开相机权限" message:@"设置-隐私-相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
= 100;
[alertView show];
return NO;
}
else{
return YES;
}
return YES;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 0 && == 100) {
NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
}
if (buttonIndex == 1 && == 100) {
[self disMiss];
}
}
3.创建相机属性
- (void)customCamera
{
//使用AVMediaTypeVideo 指明代表视频,默认使用后置摄像头进行初始化
= [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//使用设备初始化输入
= [[AVCaptureDeviceInput alloc]initWithDevice: error:nil];
//生成输出对象
= [[AVCaptureMetadataOutput alloc]init];
//照片输出
_capturePhotoOutput = [[AVCapturePhotoOutput alloc]init];
NSDictionary *outputformat = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
AVCapturePhotoSettings *outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:outputformat];
//自动闪光
[outputSettings setFlashMode:AVCaptureFlashModeAuto];
[_capturePhotoOutput capturePhotoWithSettings:outputSettings delegate:self];
//生成会话,用来结合输入输出
= [[AVCaptureSession alloc]init];
//直接设置质量最高 不指定,免得有些旧设备崩溃
if ([ canSetSessionPreset:AVCaptureSessionPresetHigh]) {
[ setSessionPreset:AVCaptureSessionPresetHigh];
}
if ([ canAddInput:]) {
[ addInput:];
}
//将设备输出添加到会话中
if ([_captureSession canAddOutput:_capturePhotoOutput]) {
[_captureSession addOutput:_capturePhotoOutput];
}
//使用,初始化预览层,负责驱动input进行信息的采集,layer负责把图像渲染显示
= [[AVCaptureVideoPreviewLayer alloc]initWithSession:];
= CGRectMake(0, 0, KScreenWidth, KScreenHeight);
= AVLayerVideoGravityResizeAspectFill;
[ addSublayer:];
//开始启动
[ startRunning];
//修改设备的属性,先加锁
if ([ lockForConfiguration:nil]) {
//自动白平衡
if ([ isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
[ setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
}
//解锁
[ unlockForConfiguration];
}
}
4.点击屏幕对焦 (这里差不多就是 和系统动画一样,点击屏幕时,设置view动画和device的point)
- (void)focusGesture:(UITapGestureRecognizer*)gesture{
CGPoint point = [gesture locationInView:];
[self focusAtPoint:point];
}
- (void)focusAtPoint:(CGPoint)point{
CGSize size = ;
// focusPoint 函数后面Point取值范围是取景框左上角(0,0)到取景框右下角(1,1)之间,按这个来但位置就是不对,只能按上面的写法才可以。前面是点击位置的y/PreviewLayer的高度,后面是1-点击位置的x/PreviewLayer的宽度
CGPoint focusPoint = CGPointMake( / ,1 - / );
if ([ lockForConfiguration:nil]) {
if ([ isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
[ setFocusPointOfInterest:focusPoint];
[ setFocusMode:AVCaptureFocusModeAutoFocus];
}
if ([ isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) {
[ setExposurePointOfInterest:focusPoint];
//曝光量调节
[ setExposureMode:AVCaptureExposureModeAutoExpose];
}
[ 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;
}];
}];
}
}
5.开启闪光灯
- (void)FlashOn{
if ([_device lockForConfiguration:nil]) {
if (_isflashOn) {
if ([_device isFlashModeSupported:AVCaptureFlashModeOff]) {
[_device setFlashMode:AVCaptureFlashModeOff];
_isflashOn = NO;
[_flashButton setTitle:@"闪光灯关" forState:UIControlStateNormal];
}
}else{
if ([_device isFlashModeSupported:AVCaptureFlashModeOn]) {
[_device setFlashMode:AVCaptureFlashModeOn];
_isflashOn = YES;
[_flashButton setTitle:@"闪光灯开" forState:UIControlStateNormal];
}
}
[_device unlockForConfiguration];
}
}
6.切换前后摄像头
- (void)changeCamera{
//获取摄像头的数量
NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
//摄像头小于等于1的时候直接返回
if (cameraCount <= 1) return;
AVCaptureDevice *newCamera = nil;
AVCaptureDeviceInput *newInput = nil;
//获取当前相机的方向(前还是后)
AVCaptureDevicePosition position = [[ device] position];
//为摄像头的转换加转场动画
CATransition *animation = [CATransition animation];
= [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
= 0.5;
= @"oglFlip";
if (position == AVCaptureDevicePositionFront) {
//获取后置摄像头
newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
= kCATransitionFromLeft;
}else{
//获取前置摄像头
newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
= kCATransitionFromRight;
}
[ addAnimation:animation forKey:nil];
//输入流
newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
if (newInput != nil) {
[ beginConfiguration];
//先移除原来的input
[ removeInput:];
if ([ canAddInput:newInput]) {
[ addInput:newInput];
= newInput;
} else {
//如果不能加现在的input,就加原来的input
[ addInput:];
}
[ commitConfiguration];
}
}
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for ( AVCaptureDevice *device in devices )
if ( == position ) return device;
return nil;
}
7.拍照---保存
#pragma mark- 拍照
- (void)shutterCamera
{
AVCaptureConnection * videoConnection = [ connectionWithMediaType:AVMediaTypeVideo];
if (videoConnection == nil) {
return;
}
[ captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
if (imageDataSampleBuffer == nil) {
return;
}
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
[self saveImageWithImage:[UIImage imageWithData:imageData]];
}];
}
/**
* 保存图片到相册
*/
- (void)saveImageWithImage:(UIImage *)image {
// 判断授权状态
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status != PHAuthorizationStatusAuthorized) return;
dispatch_async(dispatch_get_main_queue(), ^{
NSError *error = nil;
// 保存相片到相机胶卷
__block PHObjectPlaceholder *createdAsset = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
createdAsset = [PHAssetCreationRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset;
} error:&error];
if (error) {
NSLog(@"保存失败:%@", error);
return;
}
});
}];
}