views:

674

answers:

2

Hi Guys,

im trying to do an animation with an uiimageview. in this view is an image with an arrow, that i want to rotate about 45 degrees back and forward very smoothly like an pendular or an old clock. something like this, just smooth and with my image: http://bit.ly/cArvNw (found this with google ;) )

my current setup looks like this:

    UIImageView* rotatingImage = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 10.0, 200.0, 200.0)];
    [rotatingImage setImage:[UIImage imageNamed:@"wind.png"]];

    CALayer *layer = rotatingImage.layer;
    CAKeyframeAnimation *animation;
    animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.duration = 0.5f;
    animation.cumulative = YES;
    animation.repeatCount = 100;
    animation.values = [NSArray arrayWithObjects:           // i.e., Rotation values for the 3 keyframes, in RADIANS
                        [NSNumber numberWithFloat:[self degreesToRadians:45.0]], 
                        [NSNumber numberWithFloat:[self degreesToRadians:-45.0]], nil]; 
    animation.keyTimes = [NSArray arrayWithObjects:     // Relative timing values for the 3 keyframes
                          [NSNumber numberWithFloat:0], 
                          [NSNumber numberWithFloat:.5], nil]; 
    animation.timingFunctions = [NSArray arrayWithObjects:
                                 [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn],        // from keyframe 1 to keyframe 2
                                 [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut], nil]; // from keyframe 2 to keyframe 3
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;

    [layer addAnimation:animation forKey:nil];

    [self addSubview:rotatingImage];

this is really a pain, add 45 degrees, then 45 degrees backward with "-45" doesnt work. im very new to core animation and dont know how to setup my code, to get my wanted animation.

can anybody help please?

+1  A: 

Note: This method does not use Core Animation, but it's very simple and probably uses less resources.

First, make the UIImageView twice as tall, thereby making the center of rotation equal to the center of the image.

Then, define these in the @interface of the header file (of, say, your UIViewController):

BOOL goingCW; // going clockwise = YES, going counterclockwise = NO
CGFloat angle; // angle by which to change the image's rotation value

Then put this in an init method that runs once:

goingCW = YES; // change this to NO to make it start rotating CCW instead
angle = 0;

[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(update) userInfo:nil repeats:YES];

Then define update, given that arrow is the UIImageView instance:

- (void)update {
    if (goingCW) {
        if (angle > M_PI / 4) goingCW = NO; // M_PI / 4 is equal to 45 degrees
        angle += M_PI / 60; // increase 60 to slow down the rotation, etc.
    } else {
        if (angle < -M_PI / 4) goingCW = YES; // -M_PI / 4 is equal to -45 degrees
        angle -= M_PI / 60; // increase 60 to slow down the rotation, etc.
    }

    // rotate the UIImageView appropriately
    arrow.transform = CGAffineTransformMakeRotation(angle);
}

This also assumes that you are starting in the facing-down position.

Arseniy Banayev
thats okay, but a few things. with this method i cannot make a smooth transition at the end of the angle. i heared that animating with NSTimes is a "bad thing", but i dont know. your method is the best working atm.
choise
maybe try changing the timeInterval from 0.05 (which runs 20 times a second) to 0.01 (which runs 100 times a second) or some other interval. let me know how that goes.
Arseniy Banayev
actually I just realized what you may have meant. was "a smooth transition at the end of the angle" supposed to mean a simulated gravity-type effect where a force is pulling down on the arrow and decreasing the angle change at the height of the rotation? if so, you can modify the existing code by making the incrementation of angle (i.e., the "-=" and "+=" code) a function of the current y offset of a certain point on the image. maybe make another variable that counts up and then down every iteration of -(void)update, so that since
Arseniy Banayev
[continued...] the uiimageview does not move (i.e., you cannot watch for the otherwise constant x or y positions), you can make the angle increment or decrement depend on that extra variable. does that solve your problem?
Arseniy Banayev
+2  A: 

Have you looked at Apple's Example iPhone Application, "Metronome"?

It does almost exactly what you're trying to do, using Core Animation.

粪便猴子
thanks, i looked into that, but this example is totally overloaded. i dont really find the essential part, with the plain animation.
choise
hahaha... this is typical of Apple. Their documentation and examples are the finest crap one company can ever produce. Not even M$ in all their "crappyness" can produce docs like that. It is like someone trying to explain brain surgery using twitter with 140 chars or less ... "this function does this.", "to make this work, use this"... The code samples are worst than the docs. They make a 10,000 lines code to explain how to vibrate the device, instead of creating a collection of snippets that one could understand.If it was not sites like SO and a couple of books we would be screwed.
Digital Robot