So, I am trying to implement a camera using AVFoundation. I think I do everything right. this is what i am doing
AVCaptureStillImageOutput
AVCaptureVideoPreviewLayer
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With