swift - 使用工作表对话框时 AVCaptureSession 不可见

标签 swift avcapturesession

我在带有 ViewController 的 Storyboard中有一个自定义 View ,用于显示 AVCaptureSessionPreviewLayer 的输出(在本例中为网络摄像头镜头)。在我的普通窗口中使用自定义 View 时,一切正常,我可以看到视频输出。

但是当我想在工作表对话框中使用自定义 View 时,视频不可见,即使网络摄像头指示正在运行。

这是 ViewController 代码:

import Cocoa
import AVKit

class RecordViewController: NSViewController {

    let captureSession = AVCaptureSession()
     var captureDevice : AVCaptureDevice?
     var previewLayer : AVCaptureVideoPreviewLayer?
    @IBOutlet weak var camera: NSView!

override func viewDidLoad() {
    super.viewDidLoad()

    camera.wantsLayer = true;
            camera.layer = CALayer()


            // Do any additional setup after loading the view, typically from a nib.
            captureSession.sessionPreset = AVCaptureSession.Preset.medium

            // Get all audio and video devices on this machine
            let devices = AVCaptureDevice.devices()

            // Find the FaceTime HD camera object
            for device in devices {
                print(device)

                // Camera object found and assign it to captureDevice
                if ((device as AnyObject).hasMediaType(AVMediaType.video)) {
                    print(device)
                    captureDevice = device as? AVCaptureDevice
                }
            }


            if captureDevice != nil {

                do {

                    try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice!))
                    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                    previewLayer?.frame = (self.camera.layer?.frame)!

                    // Add previewLayer into custom view
                    self.camera.layer?.addSublayer(previewLayer!)

                    // Start camera
                    captureSession.startRunning()

                } catch {
                    print(AVCaptureSessionErrorKey.description)
                }
            }    }

}

最佳答案

更改行:

previewLayer?.frame = (self.camera.layer?.frame)!

到:

previewLayer?.frame = self.camera.bounds

如果你想让你的相机填满你的 customView,也可以使用这一行:

previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill

关于swift - 使用工作表对话框时 AVCaptureSession 不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57769277/

相关文章:

arrays - 如何从数组中选择项目不重复

ios - 从 SwiftUI View 调用本地 UIViewController 函数

ios - SwiftUI 按钮图像显示为黑色

ios - 如何解决 iOS 中的 AVCaptureSession 与 AVAudioSession 冲突?

ios - 提取CVImageBufferRef的子图像

ios - 在散点图上绘制置信椭圆

ios - 将 BGRA 转换为 ARGB

ios - 为什么使用 AVCaptureSession、AVAssetWriter 和 AVPlayer 录制和重放视频会卡顿?

ios - 不能将 AVCaptureDevice 与闪光灯一起使用

iOS Swift Firebase - 如何使当前用户数据在整个应用程序中可用?