斯威夫特 3
我遇到了完全相同的问题,这是我的解决方案,以防它对其他人有所帮助。
引用包含指针的层:
@IBOutlet weak var pointerImageView: UIImageView!
定义一个变量来跟踪最后一个指针位置:
private var meterPointerRadians: CGFloat = 0
创建一个使用百分比设置仪表值的函数。例如:50% 速度
func setMeter(dialPercentage: Double) {
//define the start and end angles of your speed meter: Eg: from 90 to 180 (semi circle)
let meterLowerRangeAngle: Double = 90.0
let meterUpperRangeAngle: Double = 180.0
//calculate the angle of the pointer in radians
let range = meterUpperRangeAngle - meterLowerRangeAngle
let angle = (dialPercentage * range / 100) + meterLowerRangeAngle
let radians: CGFloat = CGFloat(angle * .pi / 180)
rotatePointer(imageView: self.pointerImageView, rotationInRadians: radians, duration: 1)
}
根据指针的最后位置顺时针或逆时针旋转指针。
func rotatePointer(imageView: UIImageView, rotationInRadians: CGFloat, duration: CFTimeInterval) {
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.fromValue = meterPointerRadians
rotationAnimation.toValue = rotationInRadians
rotationAnimation.duration = duration
rotationAnimation.isCumulative = true
rotationAnimation.fillMode = kCAFillModeBoth
rotationAnimation.isRemovedOnCompletion = false
imageView.layer.add(rotationAnimation, forKey: "pointerRotationAnimation")
meterPointerRadians = CGFloat(rotationInRadians)
}