Swift3 iOS10应用。我在故事板框架中放了一个SCNView
。我在其上面放了一个UIView
(Bring to Front)并调整大小,使其仅填充屏幕中心的一部分。
在我的viewDidLoad
我使用AVFoundation查找相机,构建会话,添加输入,进行预览,然后将该预览添加到UIView
的图层。
我得到一个白色矩形而不是预览:
我认为我错过了某个地方......
// 3D scene and vars
@IBOutlet var sceneView: SCNView!
var camera: SCNNode!
var sphere: SCNNode!
// camera scene and vars
@IBOutlet var cameraView: UIView!
var cameraSession: AVCaptureSession = AVCaptureSession()
var cameraDevice : AVCaptureDevice!
var cameraInput : AVCaptureDeviceInput!
var cameraLayer: AVCaptureVideoPreviewLayer!
override func viewDidLoad() {
... 3D setup here ...
cameraDevice = AVCaptureDevice.defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .back)
do {
let possibleCameraInput: AnyObject? = try AVCaptureDeviceInput(device: cameraDevice)
if let anInput = possibleCameraInput as? AVCaptureDeviceInput {
if cameraSession.canAddInput(anInput) {
cameraSession.addInput(anInput)
}
}
} catch _ {
//TODO handle this error
}
// add the preview layer to our imageview
if cameraSession.inputs.count > 0 {
cameraLayer = AVCaptureVideoPreviewLayer(session: cameraSession) as AVCaptureVideoPreviewLayer
cameraView.layer.addSublayer(cameraLayer)
}
cameraSession.startRunning()
答案 0 :(得分:0)
好吧,这确实只是一些缺失的步骤。你必须手动设置masksToBounds,videoGravity和框架或没有任何反应(错误?坏API?)...
let viewLayer = cameraView.layer
viewLayer.masksToBounds = true
cameraView.backgroundColor = UIColor.clear
cameraLayer = AVCaptureVideoPreviewLayer(session: cameraSession) as AVCaptureVideoPreviewLayer
cameraLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
cameraLayer.frame = cameraView.frame
cameraView.layer.addSublayer(cameraLayer)
启动并运行!