1、首先声明以下对象

#import <AVFoundation/AVFoundation.h>
//捕获设备,通常是前置摄像头,后置摄像头,麦克风(音频输入)
@property (nonatomic, strong) AVCaptureDevice *device; //AVCaptureDeviceInput 代表输入设备,他使用AVCaptureDevice 来初始化
@property (nonatomic, strong) AVCaptureDeviceInput *input; //输出图片
@property (nonatomic ,strong) AVCaptureStillImageOutput *imageOutput; //session:由他把输入输出结合在一起,并开始启动捕获设备(摄像头)
@property (nonatomic, strong) AVCaptureSession *session; //图像预览层,实时显示捕获的图像
@property (nonatomic ,strong) AVCaptureVideoPreviewLayer *previewLayer;

2、初始化各个对象

- (void)cameraDistrict
{
// AVCaptureDevicePositionBack 后置摄像头
// AVCaptureDevicePositionFront 前置摄像头
self.device = [self cameraWithPosition:AVCaptureDevicePositionFront];
self.input = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:nil]; self.imageOutput = [[AVCaptureStillImageOutput alloc] init]; self.session = [[AVCaptureSession alloc] init];
// 拿到的图像的大小可以自行设定
// 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, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64);
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];
} }

根据前后置位置拿到相应的摄像头:

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for ( AVCaptureDevice *device in devices )
if ( device.position == position ){
return device;
}
return nil;
}

3、拍照拿到相应图片:

- (void)photoBtnDidClick
{
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];
[self.view addSubview:self.cameraImageView];
}

4、保存照片到相册:

#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 = @"保存图片成功" ;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示"
message:msg
delegate:self
cancelButtonTitle:@"确定"
otherButtonTitles:nil];
[alert show];
}

5、前后置摄像头的切换

- (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);
}
}
}

6、相机的其它参数设置

//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;
}];
}];
} }

7、遇到的一些坑和解决办法

1) 前后置摄像头的切换

  前后值不能切换,各种尝试找了半天没找到有原因。后来发现我在设置图片尺寸的时候设置为1080P [self.session canSetSessionPreset: AVCaptureSessionPreset1920x1080] ,前置摄像头并不支持这么大的尺寸,所以就不能切换前置摄像头。我验证了下 前置摄像头最高支持720P,720P以内可自由切换。  当然也可以在前后置摄像头切换的时候,根据前后摄像头来设置不同的尺寸,这里不在赘述。

2)焦点位置

  CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
setExposurePointOfInterest:focusPoint 函数后面Point取值范围是取景框左上角(0,0)到取景框右下角(1,1)之间。官方是这么写的:
  The value of this property is a CGPoint that determines the receiver's focus point of interest, if it has one. A value of (0,0) indicates that the camera should focus on the top left corner of the image, while a value of (1,1) indicates that it should focus on the bottom right. The default value is (0.5,0.5).
  我也试了按这个来但位置就是不对,只能按上面的写法才可以。前面是点击位置的y/PreviewLayer的高度,后面是1-点击位置的x/PreviewLayer的宽度

3)对焦和曝光

  我在设置对焦是 先设置了模式setFocusMode,后设置对焦位置,就会导致很奇怪的现象,对焦位置是你上次点击的位置。所以一定要先设置位置,再设置对焦模式。
  曝光同上

8、写在最后

  附上demo:https://github.com/nanshanyi/photographDemo
  常用到的基本就这么多,写的并不完善,有什么不对的,欢迎大家批评指正,共同学习。

  原文:http://blog.csdn.net/qq_30513483/article/details/51198464

iOS自定义相机的更多相关文章

  1. iOS开发笔记17:自定义相机拍照

    之前用AVFoundation自定义相机做了拍照与视频相关的东西,为什么要自定义呢?主要是提供更个性化的交互设计,符合app主题,对于视频来说,也便于提供更多丰富有趣的功能.前段时间整理了下拍照部分的 ...

  2. 如何用uniapp+vue开发自定义相机插件——拍照+录像功能

    调用手机的相机功能并实现拍照和录像是很多APP与插件都必不可少的一个功能,今天智密科技就来分享一下如何基于uniapp + vue实现自定义相机界面,并且实现: 1: 自定义拍照 2: 自定义录像 3 ...

  3. 【iOS自定义键盘及键盘切换】详解

    [iOS自定义键盘]详解 实现效果展示: 一.实现的协议方法代码 #import <UIKit/UIKit.h> //创建自定义键盘协议 @protocol XFG_KeyBoardDel ...

  4. Android—实现自定义相机倒计时拍照

    这篇博客为大家介绍Android自定义相机,并且实现倒计时拍照功能 首先自定义拍照会用到SurfaceView控件显示照片的预览区域,以下是布局文件: 两个TextView是用来显示提示信息和倒计时的 ...

  5. Android相机使用(系统相机、自定义相机、大图片处理)

    本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显示出来,该例子也会涉及到Android加载大图片时候的处理(避免OOM),还有简要提一下有些人Surf ...

  6. Android自定义相机拍照、图片裁剪的实现

    最近项目里面又要加一个拍照搜题的功能,也就是用户对着不会做的题目拍一张照片,将照片的文字使用ocr识别出来,再调用题库搜索接口搜索出来展示给用户,类似于小猿搜题.学霸君等app. 其实Android提 ...

  7. wp8 自定义相机+nokia滤镜+录制amr音频

    demo截图:      代码量有点多,就不贴出来了. 备注: 1.自定义相机主要横竖屏时,对相机进行旋转. 2.播放amr格式可以在页面中直接添加MediaElement控件进行播放,或者使用Bac ...

  8. Android调用系统相机以及自定义相机

    0.综述 自定义相机,此处展示简单的相机功能,官方文档中还有相应关于视频拍摄的内容,此处不提 1.添加权限 <!--相机权限,数据存储--> <uses-permission and ...

  9. iOS自定义的UISwitch按钮

    UISwitch开关控件 开关代替了点选框.开关是到目前为止用起来最简单的控件,不过仍然可以作一定程度的定制化. 一.创建 UISwitch* mySwitch = [[ UISwitchalloc] ...

随机推荐

  1. PAT L3-008. 喊山(BFS)C4 初赛30分

    喊山(30 分) 喊山,是人双手围在嘴边成喇叭状,对着远方高山发出“喂—喂喂—喂喂喂……”的呼唤.呼唤声通过空气的传递,回荡于深谷之间,传送到人们耳中,发出约定俗成的“讯号”,达到声讯传递交流的目的. ...

  2. 查看,修改ceph节点的ceph配置命令

    标签(空格分隔): ceph,ceph运维,ceph配置 查看ceph配置 1. 查看ceph默认配置: # ceph --show-config 2. 查看 type.num 的ceph默认配置: ...

  3. 转:InnoDB Crash Recovery 流程源码实现分析

    此文章转载给登博的文章,给大家分享 InnoDB Crash Recovery 流程源码实现分析 Crash Recovery问题 本文主要分析了InnoDB整个crash recovery的源码处理 ...

  4. .Net 之Tuple 类

    Tuple是什么 按照Msdn 上说:提供用于创造元组对象的静态方法.从字面意思并不能理解他的作用:   Tuple 是个静态类,提供8个静态泛型方法:T 可以是值类型,也可是引用类型:   使用场景 ...

  5. Rails的静态资源管理(五)—— 自定义 Asset Pipeline

    官方文档:http://guides.ruby-china.org/asset_pipeline.html http://guides.rubyonrails.org/asset_pipeline.h ...

  6. 数据库:sql语句分别按日,按周,按月,按季统计金额

    如: 表:consume_record 字段:consume (money类型) date (datetime类型) 请问怎么写四条sql语句分别按日,按周,按月,按季统计消费总量. 如:1月 120 ...

  7. Python-使用unrar库时Couldn't find path to unrar library的解决办法

    在Pycharm安装完unrar后,还要安装rar官方的库 不然运行的时候会抛出Couldn't find path to unrar library的错误 Windows: 下载rarlib的库文件 ...

  8. PowerDesigner中添加约束

    唯一约束 唯一约束与创建唯一索引基本上是一回事,因为在创建唯一约束的时候,系统会创建对应的一个唯一索引,通过唯一索引来实现约束.不过唯一约束更直观的表达了对应列的唯一性,使得对应索引的目的更加清晰,所 ...

  9. Shell编程进阶 1.6 if判断的几种用法

    针对文件和目录的逻辑判断 touch .txt .txt ]; then echo ok;fi -f 判断1.txt是否是文件且是否存在,成立输出ok if [-d /tmp/ ]; then ech ...

  10. myeclipse 10破解

    因为笔者的电脑是刚买不久,忘记先给电脑分区,等软年安装差不多了才发现忘记分区,所以就备份了数据,然后分区,结果分区过程中没有异常发生,就没用备用数据,就用分过区的原数据,当时还以为没问题,结果打开my ...