[英]Animate changes in a custom UIView
I am implementing a custom circular progress bar for iOS. 我正在为iOS实现自定义循环进度栏。 In my drawRect method I have the following code:
在我的drawRect方法中,我有以下代码:
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. 每当progress属性更改时,我都会调用setNeedsDisplay()方法。
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. 问题是我想动画化此进度变化,即我不希望视图从0跳到100。我能想到的唯一方法是使用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.)
不用覆盖drawRect,而是让您的自定义视图在形状层中创建CAShapeLayer和完整的圆形路径(创建圆形路径可以就像您在代码中所做的一样。)
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. 然后创建一个CABasicAnimation,在所需的任何时间段内,将形状图层的strokeEnd属性设置为从0(不绘制任何路径)到1.0(绘制所有路径)。 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: 我在Github上有一个类似的项目:
https://github.com/DuncanMC/iOS-CAAnimation-group-demo 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.) 相反,您可以将形状层安装为视图内容层的子层(或者,您可以覆盖视图类的
layerClass
方法,以将自定义视图的层类型更改为CAShapeLayer
如果您唯一想绘制的层)您的视图是圆形动画。)
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.
您希望动画中的线宽较小。
I see that you're working in Swift. 我看到您在Swift中工作。 My sample app is in Objective-C, but the concepts are the same.
我的示例应用程序在Objective-C中,但是概念是相同的。 Let me know if you need help translating anything.
让我知道您是否需要翻译任何帮助。 (I'm "bilingual".)
(我是“双语”。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.