iOS AVFoundation实现相机功能

本文介绍了如何使用AVFoundation在iOS应用中实现相机功能,包括设备方向设置、拍照方法的编写,以及拍照后照片的处理和保存到相册的步骤。特别提到`setVideoScaleAndCropFactor:`方法用于控制焦距,并提及手势缩放焦距的后续实现。同时,文章强调了在访问相册和相机前的安全验证以及镜头切换和焦距调节的实现。
摘要由CSDN通过智能技术生成

  首先导入头文件

#import <AVFoundation/AVFoundation.h>

 导入头文件后创建几个相机必须实现的对象

     /**
     *  AVCaptureSession对象来执行输入设备和输出设备之间的数据传递
     */
    @property (nonatomic, strong) AVCaptureSession* session;
      /**
       *  输入设备
       */
    @property (nonatomic, strong) AVCaptureDeviceInput* videoInput;
      /**
       *  照片输出流
       */
    @property (nonatomic, strong) AVCaptureStillImageOutput* stillImageOutput;
      /**
       *  预览图层
       */
    @property (nonatomic, strong) AVCaptureVideoPreviewLayer* previewLayer;

AVCaptureSession控制输入和输出设备之间的数据传递
AVCaptureDeviceInput调用所有的输入硬件。例如摄像头和麦克风
AVCaptureStillImageOutput用于输出图像
AVCaptureVideoPreviewLayer镜头捕捉到得预览图层

 在viewDidLoad里面初始化所有对象

- (void)initAVCaptureSession{

self.session = [[AVCaptureSession alloc] init];

NSError *error;

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

//更改这个设置的时候必须先锁定设备,修改完后再解锁,否则崩溃
[device lockForConfiguration:nil];
//设置闪光灯为自动
[device setFlashMode:AVCaptureFlashModeAuto];
[device unlockForConfiguration];

self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
if (error) {
    NSLog(@"%@",error);
}
self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
//输出设置。AVVideoCodecJPEG   输出jpeg格式图片
NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
[self.stillImageOutput setOutputSettings:outputSettings];

if ([self.session canAddInput:self.videoInput]) {
    [self.session addInput:self.videoInput];
}
if ([self.session canAddOutput:self.stillImageOutput]) {
    [self.session addOutput:self.stillImageOutput];
}

//初始化预览图层
self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
[self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
NSLog(@"%f",kMainScreenWidth);
self.previewLayer.frame = CGRectMake(0, 0,kMainScreenWidth, kMainScreenHeight - 64);
self.backView.layer.masksToBounds = YES;
[self.backView.layer addSublayer:self.previewLayer];
 }


 然后在ViewWillAppear、ViewDidDisappear方法里开启和关闭session
- (void)viewWillAppear:(BOOL)animated{

    [super view
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值