简体   繁体   中英

Animate changes in a custom UIView

I am implementing a custom circular progress bar for iOS. In my drawRect method I have the following code:

override func drawRect(rect: CGRect) {
    // Drawing code
    let path = UIBezierPath(arcCenter: barCenter, radius: radius, startAngle: CGFloat(0.0), endAngle: CGFloat(2 * M_PI) * progress, clockwise: true)
    color.set()
    path.lineWidth = lineWidth
    path.stroke()
}

Every time the progress property changes I call the setNeedsDisplay() method.

The thing is I want to animate this progress change, ie I don't want the view to just jump from 0 to 100. The only way I can think of is using NSTimer. So may be there are some more suitable ways for doing that?

I would recommend a different approach. Instead of overriding drawRect, have your custom view create a CAShapeLayer and full circle path into the shape layer (creating the circle path can be just like you're doing in your code.)

Then create a CABasicAnimation that animates the strokeEnd property of your shape layer from 0 (none of the path is drawn) to 1.0 (all of the path is drawn) over whatever time period you want. The system then takes care of generating the intermediate frames, synchronized with the screen refresh.

You can select linear timing, ease-in, ease-out, or ease-in, ease-out timing.

I have a project on Github that does something very similar:

https://github.com/DuncanMC/iOS-CAAnimation-group-demo

Take a look at the "clock wipe animation" part of the demo. That animation looks like this:

在此处输入图片说明

In that animation it uses the shape layer as a mask for an image view. You'd instead install your shape layer as a sublayer of you view's content layer (or you could override the view class' layerClass method to change the layer type of your custom view to be a CAShapeLayer if the only thing you ever want to draw in your view is the circle animation.)

My animation also makes the circle so thick that it completely fills the bounds rectangle of the image. You'd want a smaller line thickness in your animation.

Edit:

I see that you're working in Swift. My sample app is in Objective-C, but the concepts are the same. Let me know if you need help translating anything. (I'm "bilingual".)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM