开发者

Optimize Core Graphics animated drawing (iPhone)

开发者 https://www.devze.com 2023-01-08 16:08 出处:网络
I have a loop that fires a function 30 times per second. The function changes the position of a couple of points that I use to animate. I dra开发者_如何学编程w lines through all the points, meaning th

I have a loop that fires a function 30 times per second. The function changes the position of a couple of points that I use to animate. I dra开发者_如何学编程w lines through all the points, meaning that the lines will change 30 times per second.

I draw these lines to a CGLayer, which then is drawn to a UIView in the drawRect: method. I do this because I understand that performance is improved when drawing offscreen. However, it seems that the CGLayer saves all actual lines instead of drawn pixels, since even if I clear it, the program runs slower and slower over time when more lines are drawn.

I'm asking for other ways to animate this. What's the most efficient way and why?


You should use the Core Animation framework to animate properties on the layer. You can either subclass CALayer or use a delegate to do the actual drawing. In the drawing code, you can access the property that is being interpolated and use it to move points, change the thickness of lines, or anything else that Core Graphics lets you control. Look at this example code from Apple and see how it uses the lineWidth value that is being animated.

This little tutorial by John Blackburn is one of my favorite introductions to Core Animation. There are a few different concepts to grasp, but in general it's pretty simple to create quite complex animations.

Your problem with things running slower and slower most probably has nothing to do with Core Graphics. It could be that you are accidentally creating more and more timers for example.


If you have a path that needs to animate from state to state, I'd highly recommend looking at CAShapeLayer. This layer type lets you specify two paths (with the same number of control points) and animate smoothly between them using Core Animation.

Two good articles on the subject are "Marching Ants With Core Animation" by Matt Long and "Complex Interpolation with CAShapeLayer (Free)" by Joe Ricioppo.

If you instead have portions of the image that remain the same, and you just need to composite new elements on top of that, I'd recommend drawing parts of the image into static CALayers or UIViews and then adding new views on top of that for the parts that change. Compositing of layers is much, much faster than redrawing the content of a view or layer.

0

精彩评论

暂无评论...
验证码 换一张
取 消