Live camera in UIImageView

2019-06-02 11:11发布

Does anybody know how I can get a live camera feed into an UIImageView?

I have a custom UI where I need to show the camera feed (front facing camera) so I cannot use the UIImagePickerControl.

1条回答
不美不萌又怎样
2楼-- · 2019-06-02 11:14

You need to create a capture session, and start it running. Once that's done you can add the layer from the capture session to your view:

- (void)setupCaptureSession
{
    NSError* error = nil;

    // Create the session
    _captureSession = [[AVCaptureSession alloc] init];    
    _captureSession.sessionPreset = AVCaptureSessionPresetMedium;
    AVCaptureDevice* device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

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

    [_captureSession addInput:input];
    AVCaptureVideoDataOutput* output = [[AVCaptureVideoDataOutput alloc] init];
    [_captureSession addOutput:output];

    // Configure your output.
   dispatch_queue_t queue = dispatch_queue_create("myCameraOutputQueue", NULL);
   //If you want to sebsequently use the data, then implement the delegate.
   [output setSampleBufferDelegate:self queue:queue]; 
}

Having done that, you can create a preview layer as follows:

_previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_captureSession];
[_captureSession startRunning];

And then add the preview layer to your view:

_myView.layer addSubLayer:_previewLayer];
查看更多
登录 后发表回答