Home > OS >  How to create animation inside CGContext
How to create animation inside CGContext

Time:03-15

I have a circle and I want to make it pulsate.

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

But I just don't understand how to do it inside CGContext

CodePudding user response:

Here is one way you can do it using 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)
}

CoreAnimation pulse animation circle Swift iOS

  • Related