Reputation: 6829
I have added camera preview on the half of the iPhone screen.
-(void) viewDidAppear:(BOOL)animated
{
AVCaptureSession *session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetMedium;
CALayer *viewLayer = self.vImagePreview.view.layer;
NSLog(@"viewLayer = %@", viewLayer);
AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
captureVideoPreviewLayer.frame = self.vImagePreview.view.bounds;
[self.vImagePreview.view.layer addSublayer:captureVideoPreviewLayer];
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
// Handle the error appropriately.
NSLog(@"ERROR: trying to open camera: %@", error);
}
[session addInput:input];
[session startRunning];
}
I added camera view controller in viewDidLoad method and set it's frame:
vImagePreview.view.frame = CGRectMake(0, 44, 320, 179);
But camera view isn't 320. Any idea how to set width of the camera view add this way?
Height is fine but width is about 100 wide.
It's like on this link width is 320 but camera view is from some reason smaller (width).
![enter image description here][1]
Upvotes: 3
Views: 2333
Reputation: 4946
captureVideoPreviewLayer.frame = self.vImagePreview.view.bounds;
This is the culprit.
You need to add videoGravity
(Indicates how the video is displayed within a player layer’s bounds rect.) with AVLayerVideoGravityResizeAspectFill
property
and then assign the bounds
and the last but not the least,
you need to give the x and y- coordinates that establishes the center of a rectangle.
CGRect bounds=self.vImagePreview.view.layer.bounds;
avLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
avLayer.bounds=bounds;
avLayer.position=CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
Upvotes: 11