views:

481

answers:

3

I'm trying to animate the drawing of a circle. Something the Shazaam app is doing while recording, but much simpler.
I've got this code in the drawRect: method to draw the circle:

CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(currentContext, 0.86, 0.86, 0.86, 1.0);
CGContextSetLineWidth(currentContext, kLineWidth);
CGContextStrokeEllipseInRect(currentContext, CGRectMake(0.0, 0.0, 150.0, 150.0));

I tried to animate the circle with:

[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat: 3.0f] forKey: kCATransactionAnimationDuration];
// Drawing code above
[CATransaction commit];

The only thing it does is draw the circle as stated, but it's not animated.

Can anyone help me with this?

A: 

You're not going to be able to animate drawing in this way. Instead you'll have to loop through (using NSTimer, for example), and continually redraw.

I'm not sure if this is how Shazaam works or not.

Another alternative is to create a series of images and animate them in a UIImageView.

August
A: 

The folks at Omni have posted a way to animate the content of a CALayer, which would be one method for achieving this animation. (Normally Core Animation only handles changing the size, position, rotation, or opacity of a prerendered layer, not its content.) Their example uses an animating sine wave, but you could replace that with your arc drawing.

Brad Larson
A: 

Also, if you're just creating a circular "spinner" animation, you can just create a single circular image whose line "gradients" from one to zero and rotate it. But it sounds like you're trying to actually animate the drawing of a line rather than just create a spinner, so August's suggested solution of redrawing on a timer sounds like the way to go.

erikprice