iphone – 带有宽度的另一个视图问题中的相机预览

我在iPhone屏幕的一半上添加了相机预览.

-(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];
}

我在viewDidLoad方法中添加了摄像机视图控制器并设置了它的框架:

vImagePreview.view.frame = CGRectMake(0, 44, 320, 179);

但相机视图不是320.任何想法如何设置相机视图的宽度添加这种方式?
高度很好但宽度约为100宽.
这就像在这个链接宽度是320但摄像机视图是由于某种原因较小(宽度).
![在此处输入图像说明] [1]

最佳答案
 captureVideoPreviewLayer.frame = self.vImagePreview.view.bounds;

这是罪魁祸首.

您需要使用AVLayerVideoGravityResizeAspectFill属性添加videoGravity(指示视频在播放器图层边界内的显示方式.)
然后分配边界和最后但并非最不重要的,
你需要给出建立矩形中心的x和y坐标.

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

转载注明原文:iphone – 带有宽度的另一个视图问题中的相机预览 - 代码日志