美文网首页
IOS自定义相机

IOS自定义相机

作者: 那风吹过年华 | 来源:发表于2016-11-23 17:15 被阅读0次

    //捕获设备,通常是前置摄像头,后置摄像头,麦克风(音频输入)

    @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;

    - (void)cameraDistrict{

    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.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, screenWidth, screenHeight-94);

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

    }

    }

    //拍照按钮点击事件

    - (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];

    }

    相关文章

      网友评论

          本文标题:IOS自定义相机

          本文链接:https://www.haomeiwen.com/subject/cblvpttx.html