Mac App - 根据窗口大小自动调整AVCaptureVideoPreviewLayer

时间:2018-06-18 15:45:33

标签: swift macos camera autoresize

我有一个MacOS应用程序,它在AVCaptureVideoPreviewLayer层中显示网络摄像头图像,该图层嵌入在CALayer和自定义视图中。

我无法弄清楚如何定义图层以根据窗口大小自动调整网络摄像头图像的大小。

Screenshot

请同时查看Youtube上的以下视频,其中详细显示了问题https://youtu.be/XPhjw61i26M

非常感谢你!

我正在使用的代码:

    @IBAction func startPreview_click(_ sender: Any) {

    let screenRect:CGRect = NSScreen.main!.frame      
    captureSession = AVCaptureSession()
    captureSession.sessionPreset = AVCaptureSession.Preset.high

    let webcamCaptureDevice:AVCaptureDevice = (AVCaptureDevice.default(for: AVMediaType.video))!

    // Get video dimensions
    let form = webcamCaptureDevice.activeFormat.formatDescription
    let dimensions = CMVideoFormatDescriptionGetDimensions(form)    

    let webcamInput:AVCaptureDeviceInput = (try! AVCaptureDeviceInput(device: webcamCaptureDevice))
    captureSession.addInput(webcamInput)
    //let view:NSView = NSView(frame: NSRect(x: 0, y: 0, width: 500, height: 500))
    customView1.wantsLayer = true
    videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) as AVCaptureVideoPreviewLayer

    let connection = videoPreviewLayer.connection
    connection?.automaticallyAdjustsVideoMirroring = false;
    connection?.isVideoMirrored = true

    videoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspect


    videoPreviewLayer.frame = CGRect(x: CGFloat(dimensions.width)*(-1)+customView1.frame.width,
                                     y: 0,
                                     width: CGFloat(customView1.frame.width),
                                     height: CGFloat(customView1.frame.height))


    let viewLayer:CALayer = CALayer()
    viewLayer.frame = CGRect(x: 0, y: 0, width: CGFloat(dimensions.width), height: CGFloat(dimensions.height)) // war das auf 0,0 ???
    viewLayer.addSublayer(videoPreviewLayer)
    viewLayer.sublayerTransform = CATransform3DMakeScale(-1, 1, 1)
    customView1.layer = viewLayer    
}

0 个答案:

没有答案