Search code examples
ioscore-animation

CoreAnimation rotating an object and changing it's position at the same time


What I'm trying to do is to rotate a view left and right and at the same time move it's position up and down.

Here's the code I have:

CGAffineTransform leftWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(-12.0));
CGAffineTransform rightWobble = CGAffineTransformRotate(CGAffineTransformIdentity, RADIANS(12.0));

flyingGuy.transform = leftWobble;  // starting point

[UIView beginAnimations:@"wobble" context:flyingGuy];
[UIView setAnimationRepeatAutoreverses:YES];
[UIView setAnimationRepeatCount:1000];
[UIView setAnimationDuration:1.3];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(wobbleEnded:finished:context:)];

flyingGuy.transform = rightWobble;
CGRect frame = flyingGuy.frame;
frame.origin.y += 10;
[flyingGuy setFrame:frame];

[UIView commitAnimations];


- (void)wobbleEnded:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context  {
    if ([finished boolValue]) {
        UIView* item = (UIView *)context;
        item.transform = CGAffineTransformIdentity;
    }
}

With the current code, the view size changes as it moves up or down. Any suggestions?


Solution

  • Don't set or get the frame after you have set the transform!

    From the docs:

    Warning If the transform property is not the identity transform, the value of this property is undefined and therefore should be ignored.


    What you should do instead

    Change the center property of the view. You are only changing the position anyway and this is safe when you have a transform applied.