swift - 使用工作表对话框时 AVCaptureSession 不可见
问题描述
我在带有 ViewController 的情节提要中有一个自定义视图,可以向我展示 AVCaptureSessionPreviewLayer 的输出(在本例中为网络摄像头镜头)。在我的普通窗口中使用自定义视图时,一切都很好,我看到了视频输出。
但是,当我想在工作表对话框中使用自定义视图时,即使网络摄像头指示正在运行,视频也不可见。
这是 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 - 下采样图像
- javascript - 在 C/Rust 代码中为 Node-FFI 创建结构
- git - 如何在 git log 中以 %Y%m%d 格式打印提交日期?
- notifications - 如何使浏览器通知成为按钮中的可点击链接
- android - 如何在 Jetpack Compose 中更新画布上对象的位置变化?
- javascript - 打字稿:使用函数数组键入函数,该函数返回每个函数返回类型的数组
- css - 选择器右侧的 SASS (SCSS) 加号和 & 语法 ( + & ) 的含义?
- javascript - 光滑块中的未知背景颜色
- javascript - 当我尝试将数据放入这些对象时,使用 Vuex 操作获取数据对象并得到“未捕获(承诺)类型错误”
- python - 创建一个基于对象 Django 的 id 收集数据的超链接