views:

176

answers:

2

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 draw 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?

+1  A: 

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.

Felixyz
Thanks! The problem with things running slower was that I was drawing to a context that wasn't a bitmap, but saved all the lines as actual lines, which made old lines that weren't showing draw. However drawing to a bitmap context made it work.I'll check the tutorials you sent, thank you! :)
Accatyyc
+2  A: 

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.

Brad Larson
Thanks! Time to learn about compositing.
Accatyyc