ios – 如何设置相机视图来填充它的父视图

前端之家收集整理的这篇文章主要介绍了ios – 如何设置相机视图来填充它的父视图前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我不知道这个问题是关于汽车布局的问题,还是我做错了.
我有一个UIViewController和一个UIView里面.
而我正在使用AVCaptureSession将相机视图放在其中.
问题是,当我的相机视图加载在视图内时,它不会填满该视图,所以我在左侧和右侧有空白.
我想要做的是用相机填充整个UIView.
这是我的代码
...
@IBOutlet weak var camView: UIView!
var previewLayer    : AVCaptureVideoPreviewLayer!

override func viewDidLoad() {
...
previewLayer = AVCaptureVideoPreviewLayer.layerWithSession(session) as! AVCaptureVideoPreviewLayer
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer.frame = self.camView.layer.bounds
self.camView.layer.addSublayer(previewLayer)
session.startRunning()

解决方法

在您的子视图布局后,您需要进行设置.在viewDidLayoutSubviews
-(void)viewDidLayoutSubviews
{
    [self setupAVCapture];
}


- (void)setupAVCapture {
    NSError *error = nil;

    AVCaptureSession *session = [AVCaptureSession new];
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
        [session setSessionPreset:AVCaptureSessionPreset640x480];
    else
        [session setSessionPreset:AVCaptureSessionPresetPhoto];

    // Select a video device,make an input
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];

    if ([session canAddInput:deviceInput])
        [session addInput:deviceInput];

    AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
        [previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

    previewLayer.frame = self.camView.bounds;
    [self.camView.layer addSublayer:previewLayer];
    [session startRunning];
}

可能发生的事情是,您的viewDidLoad中的边界尚未准确设置,因为子视图尚未根据其限制进行布局.当您在viewDidLayoutSubviews中为previewLayer设置框架时,将采用正确的方向.请小心,您还需要调整旋转预览,以及什么不修改我使用的代码.对不起,这不是迅速的,但这并不重要.只需将您的实例化和设置移动到viewDidLayoutSubviews

所以对于你的代码,你应该这样做:

override func viewDidLayoutSubviews() {
...
previewLayer = AVCaptureVideoPreviewLayer.layerWithSession(session) as! AVCaptureVideoPreviewLayer
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer.frame = self.camView.layer.bounds
self.camView.layer.addSublayer(previewLayer)
session.startRunning()
原文链接:https://www.f2er.com/iOS/337114.html

猜你在找的iOS相关文章