如何使用 Swift scenekit 在 IOS 上绘制摄像头视频作为背景?

2024-02-23

我正在尝试在 ios 上使用 swift 和 scenekit 开发一个增强现实应用程序。有没有办法将设备摄像头拍摄的视频绘制为场景背景?


这对我有用,

I used AVFoundation捕获设备摄像头的视频输入:

   let captureSession = AVCaptureSession()
   let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill

    if let videoDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) {
        var err: NSError? = nil
        if let videoIn : AVCaptureDeviceInput = AVCaptureDeviceInput.deviceInputWithDevice(videoDevice, error: &err) as? AVCaptureDeviceInput {
            if(err == nil){
                if (captureSession.canAddInput(videoIn as AVCaptureInput)){
                    captureSession.addInput(videoIn as AVCaptureDeviceInput)
                }
                else {
                    println("Failed to add video input.")
                }
            }
            else {
                println("Failed to create video input.")
            }
        }
        else {
            println("Failed to create video capture device.")
        }
    }
    captureSession.startRunning()

此时,根据 Apple 的文档background https://developer.apple.com/library/ios/documentation/SceneKit/Reference/SCNScene_Class/index.html#//apple_ref/occ/instp/SCNScene/background的财产SCNScene,我希望添加实例AVCaptureVideoPreviewLayer to an SCNScene's background.contents,类似于:

   previewLayer.frame = sceneView.bounds
   sceneView.scene.background.contents = previewLayer 

这将我的场景的背景颜色从默认的白色更改为黑色,但不提供视频输入。这可能是 iOS 的一个 bug?所以计划 B。相反,我添加了“AVCaptureVideoPreviewLayer”作为 a 的子层UIView的层:

 previewLayer.frame = self.view.bounds
 self.view.layer.addSublayer(previewLayer)

然后我设置了一个SCNView作为同一子视图UIView,设置SCNView要清除的背景颜色:

    let sceneView = SCNView()
    sceneView.frame = self.view.bounds
    sceneView.backgroundColor = UIColor.clearColor()
    self.view.addSubview(sceneView)

设备摄像头视频作为场景背景不可见。

我创建了一个小demo https://github.com/judson-douglas/make-camera-sceneview-background/blob/master/DrawsCameraAsBackgoundWithSceneKit/ViewController.swift.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Swift scenekit 在 IOS 上绘制摄像头视频作为背景? 的相关文章

随机推荐