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

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

这对我有用,

我使用AVFoundation捕获设备摄像头的video输入:

  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的SCNScene background属性SCNScene ,我希望将AVCaptureVideoPreviewLayer的实例添加到SCNScenebackground.contents ,例如:

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

这会将场景的背景颜色从默认白色更改为黑色,但不提供video输入。 这可能是一个iOS错误? 所以计划B.相反,我添加了’AVCaptureVideoPreviewLayer’作为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) 

设备摄像机的video现在可以看作场景的背景。

我创建了一个小型演示 。

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

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

 var background: SCNMaterialProperty! { get } 

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

例:

 let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)! scnScene.background.contents = captureDevice