在自定义框架中显示相机

时间:2016-01-31 22:45:49

标签: ios objective-c camera avfoundation

我正在尝试将相机加载到自定义CGRect中,但我无法这样做,因为看起来视图受相机方面的约束。这是我正在使用的代码:

AVCaptureSession *session = [[AVCaptureSession alloc] init];
AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (videoDevice)
{
    NSError *error;
    AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
    if (!error)
    {
        if ([session canAddInput:videoInput])
        {
            [session addInput:videoInput];
            AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
            previewLayer.frame = self.view.bounds;
            CGFloat x = self.view.bounds.origin.x;
            CGFloat y = self.view.bounds.origin.y;
            CGFloat width = self.view.bounds.size.width;
            CGFloat height = 206;
            CGRect newFrame = CGRectMake(x, y, width, height);
            previewLayer.frame = newFrame;
            [self.view.layer addSublayer:previewLayer];
            [session startRunning];
        }
    }
}

这是应用当前显示的框架:

enter image description here

但是我需要这样构图:

enter image description here

我无法弄清楚如何“解锁”相机框架或调整外观。在不降低图像质量的情况下,我想要的结果是否可行,如果是这样 - 如何?

1 个答案:

答案 0 :(得分:1)

在代码末尾添加此行:

previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;