【问题标题】:Swift - Camera with device rotation in Object DetectionSwift - 物体检测中带有设备旋转的相机
【发布时间】:2021-01-30 09:20:40
【问题描述】:
【问题讨论】:
标签:
swift
swiftui
uikit
avfoundation
coreml
【解决方案1】:
我不确定在 SwiftUI 中如何,但在 UIKit 中是这样的:
尝试设置videoGravity:
cameraView.videoPreviewLayer.videoGravity = .resizeAspectFill
然后,这应该注意方向。这是基于answer。
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
}
}