iOS 中动画雷达的最佳方法

optimal approach to animate radar in iOS

我正在尝试为 iOS 中的海军型雷达(下面的旋转部分)的航向线设置动画,如下所示:

我目前的慢速、滞后和高开销解决方案(伪代码,因为真正的 Swift 代码有点冗长):

create NSTimer to call animate() every 1/60 sec
currentAngle = 0

animate():
    create UIBezierPath from center of circle to outside edge at currentAngle
    add path to new CAShapeLayer, add layer to views layer
    add fade out CABasicAnimation to layer (reduces opacity over time)
    increase currentAngle

不使用 .gif 执行此操作的最佳方法是什么?我已经实现了上面的解决方案,但是性能(帧速率和 CPU 使用)很糟糕。你会如何解决这个问题?

你的方法太复杂了。不要在动画期间尝试 re-draw 您的图像。

将旋转的部分与淡入淡出的部分分开,分别制作动画。使每个动画绘制部分透明,以便其他动画显示。

要么创建旋转部分的静态图像,要么构建一个图层来创建该图像。

如果您创建图像,则可以使用 UIView 动画为图像视图上的旋转设置动画。

如果您创建一个绘制标题线和围绕它的渐变的图层,则使用 CABasicAnimation 为图层变换的 z 旋转设置动画。

由于 Animations in Swift / iOS 8 文章:

,我找到了一个可行的 Swift 3 解决方案
    let scanInProgress = UIImageView()
    scanInProgress.image = UIImage(named: "scanInProgress.png")
    scanInProgress.frame = CGRect(x: 150, y: 200, width: 80, height: 200)
    view.addSubview(scanInProgress)

    let fullRotation = CGFloat(Double.pi * 2)
    let duration = 2.0
    let delay = 0.0

    UIView.animateKeyframes(withDuration: duration, delay: delay, options:  [.repeat, .calculationModeLinear], animations: {

      UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1/3, animations: {
        scanInProgress.transform = CGAffineTransform(rotationAngle: 1/3 * fullRotation)
      })
      UIView.addKeyframe(withRelativeStartTime: 1/3, relativeDuration: 1/3, animations: {
        scanInProgress.transform = CGAffineTransform(rotationAngle: 2/3 * fullRotation)
      })
      UIView.addKeyframe(withRelativeStartTime: 2/3, relativeDuration: 1/3, animations: {
        scanInProgress.transform = CGAffineTransform(rotationAngle: 3/3 * fullRotation)
      })

    }, completion: { 

    })