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

lge*_*lge 6 rendering augmented-reality ios scenekit swift

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

Jud*_*las 12

这对我有用,

我曾经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()
Run Code Online (Sandbox Code Playgroud)

在这一点上,基于Apple的background属性文档SCNScene,我希望将其添加AVCaptureVideoPreviewLayer到一个SCNScenes 的实例中background.contents,例如:

   previewLayer.frame = sceneView.bounds
   sceneView.scene.background.contents = previewLayer 
Run Code Online (Sandbox Code Playgroud)

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

 previewLayer.frame = self.view.bounds
 self.view.layer.addSublayer(previewLayer)
Run Code Online (Sandbox Code Playgroud)

然后我将其设置SCNView为相同的子视图UIView,将SCNView背景颜色设置为清除:

    let sceneView = SCNView()
    sceneView.frame = self.view.bounds
    sceneView.backgroundColor = UIColor.clearColor()
    self.view.addSubview(sceneView)
Run Code Online (Sandbox Code Playgroud)

设备摄像机的视频现在可以看作场景的背景.

我创建了一个小型演示.


har*_*rtw 5

从 iOS 11 开始,您现在可以使用 AVCaptureDevice 作为对象或场景背景的材质(请参阅此处的“使用动画内容” )

例子:

 
    let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)!
    scnScene.background.contents = captureDevice
Run Code Online (Sandbox Code Playgroud)


Dav*_*ist 3

是的,您可以使用 aAVCaptureVideoPreviewLayer作为contents材质属性(只需确保为图层指定边界)。

场景视图具有背景的材质属性,您可以将视频预览分配给该属性(将图层分配给背景的内容)。

var background: SCNMaterialProperty! { get }
Run Code Online (Sandbox Code Playgroud)