AVFoundation,切断预览图层中的边缘

时间:2011-10-22 13:33:47

标签: ios

我正在开发一些iOS应用,我需要做一些相机扫描。这是我第一次使用AVFoundation,之前我使用UIImagePickerController开发了相机应用程序,但AVFoundation似乎更强大。

问题在于它会切断预览图层中的边缘,无论我将预览图层的边框设置为视图控制器的边框。

这是我的代码:

AVCaptureSession *captureSession = [[AVCaptureSession alloc] init];
    AVCaptureDevice *photoCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    AVCaptureDeviceInput *videoInput = [AVCaptureDeviceInput deviceInputWithDevice:photoCaptureDevice error:&error];
    if(videoInput){
        [captureSession addInput:videoInput];
        [captureSession startRunning];
        NSLog(@"ok");
    }   
    AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:captureSession];
    previewLayer.frame = self.view.bounds;
    NSLog(@"%f %f", previewLayer.frame.size.width, previewLayer.frame.size.height);
    [self.view.layer addSublayer:previewLayer];

非常感谢你的帮助, 阿尔乔姆

2 个答案:

答案 0 :(得分:21)

这是因为您捕获的视频的宽高比与屏幕的宽高比不同。你可以做的并不多 - 它既可以是拳击,也可以是图像的非均匀缩放。你可以丢弃短边上的一些像素,这可能是UIImagePickerController的作用。

如果您需要此行为,请尝试设置

  previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

答案 1 :(得分:8)

实际上解决方案非常简单,因为Rhythmic Fistman提到AVCaptureVideoPreviewLayer中有一个属性 - videoGravity。因此,要在自定义视图中调整预览图层:

previewLayer.frame = self.view.bounds;
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
// Specifies that the player should preserve the video’s aspect ratio and fill the layer’s bounds.

previewLayer.videoGravity = AVLayerVideoGravityResize; 
// Specifies that the video should be stretched to fill the layer’s bounds.