如何在预览视图图层

时间:2016-05-08 09:02:21

标签: ios swift

我使用下面的代码在iPhone设备上显示相机。相机可以显示UI,我可以拍照。但是,相机仅显示在previewLayer的中间。如何让相机填满AVCaptureVideoPreviewLayer上的所有空间?我试图使用AVLayerVideoGravityResizeAspectFill引力,但它会使图像变形。

self.session = AVCaptureSession()
        do {
            let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
            try self.videoInput = AVCaptureDeviceInput(device: device)
        } catch {

        }
        if ((self.session?.canSetSessionPreset(AVCaptureSessionPresetHigh)) != nil){
            self.session?.sessionPreset = AVCaptureSessionPresetHigh
        }
        self.stillImageOutput = AVCaptureStillImageOutput()

        self.stillImageOutput?.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
        if self.session!.canAddInput(self.videoInput){
            self.session?.addInput(self.videoInput)
        }
        if self.session!.canAddOutput(self.stillImageOutput){
            self.session?.addOutput(self.stillImageOutput)
        }

self.previewLayer = AVCaptureVideoPreviewLayer(session: self.session)
        //self.backView.frame = CGRectMake(0, 0, self.view.bounds.width,self.view.bounds.width)
        let viewLayer:CALayer = self.backView.layer
        viewLayer.masksToBounds = true
        let bounds:CGRect = viewLayer.bounds
        self.previewLayer?.frame = bounds
        self.previewLayer?.backgroundColor = UIColor.blackColor().CGColor
        self.previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect//AVLayerVideoGravityResizeAspect
        self.backView.layer.addSublayer(self.previewLayer!)

以下是相机的屏幕截图。

enter image description here

2 个答案:

答案 0 :(得分:5)

我这样做:

import * as THREE from 'three';

如果在viewDidLoad()中执行此操作,则可能出现错误的界限。

答案 1 :(得分:0)

尝试添加此

self.previewLayer?.frame = self.view.bounds //Or whatever size you want the previewLayer to fit.