Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVFoundation camera preview layer not working

So, I am trying to implement a camera using AVFoundation. I think I do everything right. this is what i am doing

  1. create session
  2. get devices of video type
  3. loop through devices to get the camera at the back
  4. get a device input using the device mentioned in #3 and add it to the session
  5. create an output of type AVCaptureStillImageOutput
  6. set output settings and add it to the session
  7. get a CALayer from my view 2(will explain below what I mean by view 2)
  8. create an instance of AVCaptureVideoPreviewLayer
  9. add it to the layer mentioned in #7
  10. start running the session

So I have 2 views one over the other. The one on top is View 1 and the one below is view 2. View 1 is supposed to provide with custom camera controls.

Here is the code:

self.session = [[AVCaptureSession alloc]init];
[self.session setSessionPreset:AVCaptureSessionPresetHigh];
NSArray *devices = [[NSArray alloc]init];
devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices){
    if([device position] == AVCaptureDevicePositionBack){
        self.device = device;
        break;
    }
}
NSError *error;
self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:&error];
if([self.session canAddInput:self.input]){
    [self.session addInput:self.input];    
}


self.stillImageOutput = [[AVCaptureStillImageOutput alloc]init];
NSDictionary *outputSettings = @{AVVideoCodecKey : AVVideoCodecJPEG};
[self.stillImageOutput setOutputSettings:outputSettings];

[self.session addOutput:self.stillImageOutput];

CALayer *cameraLayer = self.cameraView.layer;
self.cameraView.backgroundColor = [UIColor clearColor];

AVCaptureVideoPreviewLayer *preview = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
[cameraLayer addSublayer:preview];

[self.session startRunning];

What I get is View 1(it has a .png image as its background. the image has a hole so that the view under it, view 2 can be visible) and view 2 is visible but I dont see what I am supposed to. Because I changed the background color for view 2 to clear color I see all black. I am supposed to see what the camera sees.

like image 267
nupac Avatar asked Oct 12 '13 12:10

nupac


1 Answers

Turns out you have to set frame, maskToBounds and gravity for your preview layer to work correctly. This is how I did it

CALayer *cameraLayer = self.cameraView.layer;
self.cameraView.backgroundColor = [UIColor clearColor];
[cameraLayer setMasksToBounds:YES];
AVCaptureVideoPreviewLayer *preview = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
[preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[preview setFrame:[cameraLayer bounds]];


[cameraLayer addSublayer:preview];
like image 156
nupac Avatar answered Sep 28 '22 08:09

nupac