Alvin
Alvin

Reputation: 539

AVfoundation Camera goes off screen Obj-C

I am working on scanning barcode ios App that uses AVFoundation

So i have created a square box with constraint using the interface builder. The square box is all good with the constraints. Perfectly fine. i have this following code to add the avcapturelayer to the square box.

self.captureLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
[self.captureLayer setFrame:self.cameraPreviewView.layer.bounds];
[self.captureLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[self.cameraPreviewView.layer addSublayer:self.captureLayer];

the layer follows the leading space from the square box constraint, but not with the trailing. The new added AVlayer goes off the screen(to the right) while the square box itself is all good. What am I missing here?

thanks!

Upvotes: 0

Views: 52

Answers (3)

Dhiru
Dhiru

Reputation: 3060

This may solve your problem

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

Or

as you are you are using AVLayerVideoGravityResizeAspectFill so it will go out of screen , you can use AVLayerVideoGravityResizeAspectFit instead.

you need to set clipToBound=YES; when using AVLayerVideoGravityResizeAspectFill (when using you View )

view.clipToBound=YES;

and than add Sublayer to view

view.layer.masksToBounds = YES;

Upvotes: 0

Stefan S
Stefan S

Reputation: 741

This might be happening if you are setting the frame in viewDidLoad. If so, try doing it in viewWillAppear:instead.

Upvotes: 0

Arnaud
Arnaud

Reputation: 11

I think you should try to set self.captureLayer bounds/position instead of frame ? Cheers!

Upvotes: 0

Related Questions