问题描述
我正在使用 Swift 制作相机应用。目前,我正在努力在用户点击屏幕以更改相机的焦点和曝光时显示一个黄色方块。我可以通过点击屏幕上的某处来更改相机对焦和曝光。但是,当我尝试在用户点击的位置显示黄色方块时,它总是显示在 iPhone 的左上角。 (我的意思是......例如,如果我按下屏幕中央来改变焦点,相机应用程序将聚焦到中心,但黄色方块,指示聚焦的位置,出现在屏幕的左上角。)
这是测试设备的屏幕。如您所见,即使我点击了屏幕中央,左上角仍有一个黄色方块。
这是我的代码的一部分。
final class ViewController: UIViewController {
@IBOutlet private weak var lfView: MTHKView!
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var pointOfInterestView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
pointOfInterestView.layer.borderWidth = 1
pointOfInterestView.layer.borderColor = UIColor.systemYellow.cgColor
// more codes...
}
// camera focus
func setFocus(focusMode: AVCaptureDevice.FocusMode,exposureMode: AVCaptureDevice.ExposureMode,atPoint devicePoint: CGPoint,shouldMonitorSujectAreaChange: Bool) {
// camera can now change focus and exposure at tapped place
}
override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
let touchPoint = touches.first! as UITouch
let screenSize = lfView.bounds.size
let focusPoint = CGPoint(x: touchPoint.location(in: lfView).y / screenSize.height,y: 1.0 - touchPoint.location(in: lfView).x / screenSize.width)
print("focus point \(focusPoint)")
showPointOfInterestViewAtPoint(point: focusPoint)
setFocus(focusMode: .autoFocus,exposureMode: .autoExpose,atPoint: focusPoint,shouldMonitorSujectAreaChange: true)
}
func showPointOfInterestViewAtPoint(point: CGPoint) {
pointOfInterestHalfCompletedWorkItem = nil
pointOfInterestComplatedWorkItem = nil
pointOfInterestView.center = point
print("point of interest\(point)")
pointOfInterestView.transform = CGAffineTransform(scaleX: 1.5,y: 1.5)
let animation = UIViewPropertyAnimator(duration: 0.3,curve: .easeInOut) {
print("animation is called")
self.pointOfInterestView.transform = .identity
self.pointOfInterestView.alpha = 1
}
animation.startAnimation()
}
}
我放了两个打印,分别是 focus point
和 point of interest
,它们显示相同的值,例如 (0.6326836581709145,0.46399999999999997)。
我认为编写 pointOfInterestView.center = point
会将视图的位置更改为点击的位置。
如果我做错了什么,你能指出我吗,或者我应该在哪里解决这个问题?
解决方法
在计算焦点时,您将 x 和 y 坐标除以屏幕宽度和高度。这实质上将它们转换为百分比(这就是为什么您会看到这些小十进制值)。
如果你想要实际点(这似乎是你以后使用的),不要除以屏幕大小。