获取相机预览到AVCaptureVideoPreviewLayer [英] Get Camera Preview to AVCaptureVideoPreviewLayer

查看:555
本文介绍了获取相机预览到AVCaptureVideoPreviewLayer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让相机输入显示在预览图层视图上。

I was trying to get the camera input to show on a preview layer view.

self.cameraPreviewView与IB中的UIView绑定

self.cameraPreviewView is tied to a UIView in IB

这是我目前使用AV Foundation Programming Guide编写的代码。但预览从未显示

Here is my current code that I put together from the AV Foundation Programming Guide. But the preview never shows

AVCaptureSession *session = [[AVCaptureSession alloc] init];
    session.sessionPreset = AVCaptureSessionPresetHigh;

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];

    if (!input) {
        NSLog(@"Couldn't create video capture device");
    }
    [session addInput:input];


        // Create video preview layer and add it to the UI
        AVCaptureVideoPreviewLayer *newCaptureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
        UIView *view = self.cameraPreviewView;
        CALayer *viewLayer = [view layer];

        newCaptureVideoPreviewLayer.frame = view.bounds;

        [viewLayer addSublayer:newCaptureVideoPreviewLayer];

        self.cameraPreviewLayer = newCaptureVideoPreviewLayer;



        [session startRunning];


推荐答案

经过一些试验和错误,看着苹果公司的AVCam示例代码

So after some trial and error and looking at apple's AVCam Sample Code

我将PreviewLayer代码和会话startRunning包装成一个像这样的大型中央调度块,它开始工作。

I wrapped the PreviewLayer code and session startRunning into a grand central dispatch block like so and it started working.

 dispatch_async(dispatch_get_main_queue(), ^{
    AVCaptureVideoPreviewLayer *newCaptureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    UIView *view = self.cameraPreviewView;
    CALayer *viewLayer = [view layer];

    newCaptureVideoPreviewLayer.frame = view.bounds;

    [viewLayer addSublayer:newCaptureVideoPreviewLayer];

    self.cameraPreviewLayer = newCaptureVideoPreviewLayer;

    [session startRunning];
});

这篇关于获取相机预览到AVCaptureVideoPreviewLayer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆