如何在 CGContext 中创建动画

How to create animation inside CGContext

我有一个圆圈,我想让它有脉动。

func drawCircle(context: CGContext) {
    let circle = CGRect(x: circleX, y: circleY, width: circleDiameter, height: circleDiameter)
    context.setFillColor(UIColor.systemPink.cgColor)
    context.addEllipse(in: circle)
}

但我只是不明白如何在 CGContext 中做到这一点

这是使用 CoreAnimation 的一种方法:

func drawCircle(context: CGContext) {
    context.setFillColor(UIColor.systemPink.cgColor)
    
    context.addEllipse(in: CGRect(x: bounds.origin.x,
                                  y: bounds.origin.y,
                                  width: bounds.width,
                                  height: bounds.height))
    
    context.fillPath()
    
    // Using CoreAnimation
    let animation = CABasicAnimation(keyPath: "transform.scale")
    animation.repeatCount = .infinity
    animation.duration = 2
    animation.toValue = 1.5
    animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
    animation.autoreverses = true
    
    layer.add(animation, forKey: nil)
}