AVCaptureVideoPreviewLayer doesn't fill up whole iPhone 4S Screen

AVCaptureVideoPreviewLayer *avLayer = 
                [AVCaptureVideoPreviewLayer layerWithSession:session];
avLayer.frame = self.view.frame;
[self.view.layer addSublayer:avLayer];

I use AVCaptureVideoPreviewLayer to display video on the view. But the video's view didn't fill up the full iPhone4's screen.(two grey bar at the right&left side)

I want the video fills up full screen. How can I deal with it? Thank you very much!

enter image description here


Solution 1:

Maybe this solves it?

CGRect bounds=view.layer.bounds;
avLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
avLayer.bounds=bounds;
avLayer.position=CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));

Solution 2:

One potential cause of confusion is that the AVCaptureVideoPreviewLayer is a CoreAnimation layer and in all of the answers above is being positioned statically (e.g. without constraints) relative a view. If you use constraints to layout the view, these don't automatically resize the preview layer.

This means that you cannot set up the preview layer in viewDidLoad as the layout has not yet taken place and the preview layer will sized how it was in Interface Builder.

Instead, override viewDidLayoutSubviews on your ViewController and position the preview layer there.

- (void)viewDidLayoutSubviews
{
    CGRect bounds=view.layer.bounds;
    avLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;  
    avLayer.bounds=bounds;
    avLayer.position=CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
}