Swift - 在对象检测中使用设备旋转的相机

Swift - Camera with device rotation in Object Detection

我正在看这个教程 (https://developer.apple.com/documentation/vision/recognizing_objects_in_live_capture),问题是当你旋转设备时,相机的视图不会改变帧大小,所以你会有一个黑色 space.

有解决这个问题的想法吗?

此外,我在 SwiftUI 中制作了我的应用程序版本(但问题仍然存在),因此也感谢使用 SwiftUI 的解决方案!

提前致谢

我不确定在 SwiftUI 中如何,但在 UIKit 中是这样:

尝试设置 videoGravity:

cameraView.videoPreviewLayer.videoGravity = .resizeAspectFill

那么,这应该会注意方向。这是基于此 .

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    
    let cameraPreviewTransform = self.cameraView.transform
    
    coordinator.animate { (context) in
        
        let deltaTransform = coordinator.targetTransform
        let deltaAngle: CGFloat = atan2(deltaTransform.b, deltaTransform.a)
        
        var currentRotation = atan2(cameraPreviewTransform.b, cameraPreviewTransform.a)
        
        // Adding a small value to the rotation angle forces the animation to occur in a the desired direction, preventing an issue where the view would appear to rotate 2PI radians during a rotation from LandscapeRight -> LandscapeLeft.
        currentRotation += -1 * deltaAngle + 0.0001;
        self.cameraView.layer.setValue(currentRotation, forKeyPath: "transform.rotation.z")
        self.cameraView.layer.frame = self.view.bounds
    } completion: { (context) in
        let currentTransform : CGAffineTransform = self.cameraView.transform
        self.cameraView.transform = currentTransform
    }
}