阅读 633

iOS拍照定制之AVCapturePhotoOutput

  • 问题

    领导安排任务,写个拍照功能,界面跟系统拍照有点出入

    拍完照片,底部显示已拍照片,有个拍照上限[在此不论]

    点击已拍照片,可以预览、放大缩小查看

  • 思路

    系统拍照肯定不行了,只能定制,没提是否拍照禁止声音的需求[非偷拍,正经人]

    原则上能简单就不复杂,拍砖AVCapturePhotoOutput

  • 捋捋

    首先,你需要一块暂时当前场景的layer,这里不提,参考上篇[iOS写在定制相机之前]

    其次,定义session + photoOutput

    再次,定义拍照事件

    最后,代理中获得照片

  • 上菜

    • session定义 input设置
    self.session = [[AVCaptureSession alloc] init];
    self.session.sessionPreset = AVCaptureSessionPresetPhoto;
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    self.dInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    if ([self.session canAddInput:self.dInput]) {
        [self.session addInput:self.dInput];
    }
    复制代码
    • 拍照场景layer
    self.preView = [[AVPreView alloc] init];
    self.preView.backgroundColor = [UIColor colorWithHexs:0x3f3f3f];
    self.preView.session = self.session;
    [self.preView setVideoOrientation:AVCaptureVideoOrientationLandscapeRight];
    [self.view addSubview:self.preView];
    [self.preView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(self.topView.mas_bottom);
        make.bottom.equalTo(self.collect.mas_top);
        make.right.equalTo(rightView.mas_left);
    }];
    复制代码
    • 设置photoOutput
    self.photoOutput = [[AVCapturePhotoOutput alloc] init];
    if ([self.session canAddOutput:self.photoOutput]) {
        [self.session addOutput:self.photoOutput];
    }
    [self.photoOutput.connections.lastObject setVideoOrientation:AVCaptureVideoOrientationLandscapeRight];
    复制代码
    • session start
    [self.session startRunning];
    复制代码
    • 拍照点击
    AVCapturePhotoSettings *set = [AVCapturePhotoSettings photoSettings];
    [self.photoOutput capturePhotoWithSettings:set delegate:self];
    复制代码
    • AVCapturePhotoCaptureDelegate
    #pragma mark - AVCapturePhotoCaptureDelegate
    -(void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error  API_AVAILABLE(ios(11.0)) {
        if (!error) {
            // 使用该方式获取图片,可能图片会存在旋转问题,在使用的时候调整图片即可
            NSData *data = [photo fileDataRepresentation];
            UIImage *image = [UIImage imageWithData:data];
            
            // 对,就是上面的image
        }
    }
    
    复制代码
  • Game Over.

    See me Tomorrow, haha

文章分类
iOS
文章标签