工具类:
// Created by hdf on 2022/3/31.
import UIKit
class UIOneFingerRotationGes: UIGestureRecognizer {
var rotation: CGFloat = 0.0
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
if (event.touches(for: self)?.count ?? 0) > 1 {
self.state = .failed
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
if self.state == .possible {
self.state = .began
} else {
self.state = .changed
}
guard let touch = touches.first, let view = self.view else { return }
let center = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
let currentTouchPoint = touch.location(in: view)
let previousTouchPoint = touch.previousLocation(in: view)
let f1 = Float(currentTouchPoint.y - center.y)
let f2 = Float(currentTouchPoint.x - center.x)
let f3 = Float(previousTouchPoint.y - center.y)
let f4 = Float(previousTouchPoint.x - center.x)
let angle = atan2f(f1, f2) - atan2f(f3, f4)
self.rotation = CGFloat(angle)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
if state == .changed {
state = .ended
} else {
state = .failed
}
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
state = .cancelled
}
}
使用方法:
let oneRotate = UIOneFingerRotationGes(target: self, action: #selector(oneFingerRotateAction(ges:)))
compassImgV.addGestureRecognizer(oneRotate)
@objc private func oneFingerRotateAction(ges: UIOneFingerRotationGes) {
compassImgV.transform = compassImgV.transform.rotated(by: ges.rotation)
}
|