Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display overlay over AVCaptureVideoPreviewLayer

I need to display image(frame) overlay over AVCaptureVideoPreviewLayer. How can i do this?

-(void) viewDidAppear:(BOOL)animated
{
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    session.sessionPreset = AVCaptureSessionPresetPhoto;
    [session commitConfiguration];

    CALayer *viewLayer = self.vImagePreview.layer;
    NSLog(@"viewLayer = %@", viewLayer);

    AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];

    captureVideoPreviewLayer.frame = self.vImagePreview.bounds;
    [self.vImagePreview.layer addSublayer:captureVideoPreviewLayer];

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (!input) {
        // Handle the error appropriately.
        NSLog(@"ERROR: trying to open camera: %@", error);
    }
    [session addInput:input];

    _stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
    [_stillImageOutput setOutputSettings:outputSettings];

    [session addOutput:_stillImageOutput];

    [session startRunning];

}

Adding new view over the video output layer does not work. The preview layer appear on top of all views.

My view hierarchy:

  • MainView
    • OverlayView
    • VideoOutputView

My frame appears under the video output view

like image 418
TUNER88 Avatar asked Oct 21 '22 04:10

TUNER88


1 Answers

Even though this question was asked N years ago, I would like to share my exact answer. After few minutes, I was able to comprehend what Gujamin said. Indeed, the solution can be do it programmatically. But in case you're doing in XIB or Storyboard, check this kind of hierarchy. Don't put any subviews to your CameraPreviewView (the uiview which its layer will be the camera).

enter image description here

like image 118
Citus Avatar answered Oct 24 '22 04:10

Citus