SWIFT 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)
}