How to animate drawing in Swift, but also change a UIImageView's scale?

后端 未结 3 1408
迷失自我
迷失自我 2021-01-01 07:03

I\'d like to animate a drawing sequence. My code draws a spiral into a UIImageView.image. The sequence changes the image contents, but also changes the scale

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-01 07:46

    @Matt provided the answer and gets the checkmark. I'll recap some points for emphasis:

    • UIView animation is great for commonly animated properties, but if you need to vary a property not on UIView's animatable list, you can't use it. You must create a new CALayer and add a CABasicAnimation(keyPath:) to it.
    • I tried but was unable to get my CABasicAnimations to fire by adding them to the default UIView.layer. I needed to create a custom CALayer sublayer to the UIView.layer - something like myView.layer.addSublayer(myLayer)
    • Leave the custom sublayer installed and re-add the CABasicAnimation to that sublayer when (and only when) you want to animate drawing.
    • In the custom CALayer object, be sure to override class func needsDisplay(forKey key: String) -> Bool with your key property (as @Matt's example shows), and also override func draw(in cxt: CGContext) to do your drawing. Be sure to decorate your key property with @objc. And reference the key property within the drawing code.
    • A "gotcha" to avoid: in the UIView object, be sure to null out the usual draw method (override func draw(_ rect: CGRect) { }) to avoid conflict between animated and non-animated drawing on the separate layers. For coordinating animated and non-animated content in the same UIView, it's good (necessary?) to do all your drawing from your custom layer.
    • When doing that, use myLayer.setNeedsDisplay() to update the non-animated content within the custom layer; use myLayer.add(myBasicAnimation, forKey:nil) to trigger animated drawing within the custom layer.

    As I said above, @Matt answered - but these items seemed worth emphasizing.

提交回复
热议问题