views:

747

answers:

1

Hi all,

I have a case where i'm drawing shapes, e.g. a Triangle (Points A, B, C). Now i want to animate it so that Points A, B, C move towards Point X, Y, Z. (Lets just say on button click)

I'm using a drawRect: method in my custom view for drawing. I don't want my view to move, i rather want my drawing to move (because i have multiple drawings).

Any pointers? Any relative articles?

Regards, Mustafa

+1  A: 

Core Animation is a good solution for this type of thing. You have CAShapeLayer that allows you to draw shapes according to a path and you can animate using a basic animation or a keyframe animation. You can do something like this in your button click:

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
[animation setFromValue:[NSValue valueWithCGPoint:CGPointMake(0.0, 0.0)]];
[animation setToValue:[NSValue valueWithCGPoint:CGPointMake(320.0, 480.0)]];
[animation setDuration:2.0f];
[shapeLayer addAnimation:animation forKey:@"positionAnimation"];

This will animate the layer from point 0.0, 0.0 (upper left hand corner) to 320.0, 480.0 (lower right hand corner) over the course of two seconds. When you add the animation to your layer, it will start playing immediately. If you are looking to rotate the animation (wasn't sure from the post), you can do this:

CABasicAnimation *rotationAnimation;
rotationAnimation = [CABasicAnimation 
             animationWithKeyPath:@"transform.rotation.z"];

[rotationAnimation setFromValue:DegreesToNumber(0)];
[rotationAnimation setToValue:DegreesToNumber(360)];
[rotationAnimation setDuration:2.0f];
[rotationAnimation setRepeatCount:10000]; // keep spinning

[shapeLayer addAnimation:rotationAnimation forKey:@"rotate"];

The DegreesToNumber is a helper function that converts degrees to radians and returns an NSNumber object:

CGFloat DegreesToRadians(CGFloat degrees)
{
    return degrees * M_PI / 180;
}

NSNumber* DegreesToNumber(CGFloat degrees)
{
    return [NSNumber numberWithFloat:
            DegreesToRadians(degrees)];
}

There are lots of articles on the web about Core Animation, but this should get you started. Let me know if you need clarification.

Matt Long
Thanks Matt, I'll test it out and will let you know how it goes.
Mustafa