为什么我的预览图层不会覆盖整个视图?

时间:2017-07-30 22:24:36

标签: ios iphone swift avfoundation

我正在使用AVFoundation相机制作iPhone应用程序,但相机无法正确缩放。

我认为我做了很多工作以使其大小相同,我将视频重力更改为ResizeAspectFill并将previewlayer.frame.size更改为self.layer.frame.size。

为什么我的预览图层不会覆盖整个视图?这是我输入错误或忘记我需要输入的东西吗?谢谢!

图片:http://imgur.com/O713SoE

代码:

import AVFoundation
import UIKit
import QuartzCore

class View1: UIViewController {

    let captureSession = AVCaptureSession()
    var previewLayer: CALayer!
    var captureDevice: AVCaptureDevice!

    @IBOutlet weak var photoButton: UIButton!
    @IBOutlet weak var cameraView:  UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        photoButton.layer.zPosition = 1
    }

    @IBAction func photoButtonpressed(_ sender: UIButton) {
        let button = sender as UIButton
        if (button.tag == 1){
            print("Photobutton clicked")        
        }
    }

    func prepareCamera(){

        captureSession.sessionPreset = AVCaptureSessionPreset1920x1080

        if let availableDevices = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInWideAngleCamera],
                                                                               mediaType: AVMediaTypeVideo,
                                                                               position: .back).devices {

            captureDevice = availableDevices.first

            beginSession()  
        }
    }

    func beginSession(){
        do {
            let captureDeviceInput = try AVCaptureDeviceInput(device: captureDevice)
            captureSession.addInput(captureDeviceInput)       
        } catch {  
            print(error.localizedDescription)
        }

        if let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession){

            self.previewLayer = previewLayer

            self.view.layer.addSublayer(self.previewLayer)

            self.previewLayer.frame = self.view.layer.frame
            self.previewLayer.bounds = self.view.bounds
            self.previewLayer.contentsGravity = AVLayerVideoGravityResizeAspectFill

            captureSession.startRunning()

            let dataOutput = AVCaptureVideoDataOutput()

            dataOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString): NSNumber(value: kCVPixelFormatType_32BGRA)]

            dataOutput.alwaysDiscardsLateVideoFrames = true

            if captureSession.canAddOutput(dataOutput) {
                captureSession.addOutput(dataOutput)
                captureSession.commitConfiguration()        
            }
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)    
        prepareCamera()    
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

1 个答案:

答案 0 :(得分:0)

我复制了您的代码并在iOS 10.1.1iPhone6XCode 8.2.1上运行。 Screen shot of your workable code

如何加载View1?编程?在故事板中发起? view的{​​{1}}可能与您的设备屏幕大小不同。