How to set camera view to fill it's parent view How to set camera view to fill it's parent view ios ios

How to set camera view to fill it's parent view


You need to conduct the setup after your subviews are layed out. In viewDidLayoutSubviews

Add view

Add outlet

Add Constraints

-(void)viewDidLayoutSubviews{    [self setupAVCapture];}- (void)setupAVCapture {    NSError *error = nil;    AVCaptureSession *session = [AVCaptureSession new];    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)        [session setSessionPreset:AVCaptureSessionPreset640x480];    else        [session setSessionPreset:AVCaptureSessionPresetPhoto];    // Select a video device, make an input    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];    if ([session canAddInput:deviceInput])        [session addInput:deviceInput];    AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];        [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];    previewLayer.frame = self.camView.bounds;    [self.camView.layer addSublayer:previewLayer];    [session startRunning];}

What was likely happening to you is that the bounds were not accurately set yet in your viewDidLoad as the subviews have yet to be laid out according to their constraints. When you instead setup the frame for the previewLayer in viewDidLayoutSubviews it will adopt the correct orientation. Be careful though, you will also need to adjust the preview on rotation and what not and modify the code I used. Sorry it isn't in swift, but that shouldn't matter. Just move your instantiation and setup into viewDidLayoutSubviews

So for your code, you should do something like this:

override func viewDidLayoutSubviews() {...previewLayer = AVCaptureVideoPreviewLayer.layerWithSession(session) as! AVCaptureVideoPreviewLayer    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFillpreviewLayer.frame = self.camView.layer.boundsself.camView.layer.addSublayer(previewLayer)session.startRunning()


To set priviewLayer constraints as like below code so it will occupied whole screen.

Leading Space = 0 from mainViewTop Space = 0 from mainViewBottom Space = 0 from mainView Trailing Space = 0 from mainView

Hope this help you.


This worked for me in Swift 4.2

Just set your AVCaptureVideoPreviewLayer's instance frame to Parent view's frame like below in viewDidLayoutSubviews() function :

override func viewDidLayoutSubviews(){        super.viewDidLayoutSubviews()        avCaptureVideoPreviewLayerInstance.frame = self.parentView.bounds    }