Search code examples
iphoneipadiosuiviewcgaffinetransform

Animated moving and rotating a UIView doesn't quite work


I want to create an animation that moves and rotates a UIView at the same time. I tried the following code:

[UIView beginAnimations:@"MoveAndRotateAnimation" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; 
[UIView setAnimationDuration:kAnimationDuration];

myView.frame = newFrame;
myView.transform = CGAffineTransformMakeRotation(0.4);

[UIView commitAnimations];

The result is, that after the animation has finished the view is drawn incorrectly (some parts are not visible anymore). If I only change the frame OR the transformation for the animation, the view draws correctly. The problem only occurs if I set both the frame and transformation.

What would be the correct way to animate moving and rotating of a view at the same time?


Solution

  • You can't use frame, bounds, or center if you are also animating things like rotation. You need to use CGAffineTransforms for everything and concatenate them together. Like so:

    CGAffineTransform transform = CGAffineTransformMakeTranslation(100,100);
    transform = CGAffineTransformRotate(transform, 0.4);
    
    [UIView beginAnimations:@"MoveAndRotateAnimation" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; 
    [UIView setAnimationDuration:kAnimationDuration];
    
    myView.transform = transform;
    
    [UIView commitAnimations];