Search code examples
rotationtransformcgaffinetransform

CGAffineTransformMakeRotation not working when called for the second time


I have this function to rotate UIButtons 45 degrees. But once its rotated, recalling the same method does not make any more rotation and the button is stuck at its rotated position after the first rotation. Any ideas?

- (void)rotateImage:(UIButton *)image duration:(NSTimeInterval)duration 
              curve:(int)curve degrees:(CGFloat)degrees
{
    // Setup the animation
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:duration];
    [UIView setAnimationCurve:curve];
    [UIView setAnimationBeginsFromCurrentState:YES];

    // The transform matrix
    CGAffineTransform transform = 
    CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(degrees));
    image.transform = transform;

    // Commit the changes
    [UIView commitAnimations];
}

Solution

  • The transform property is absolute. If you want relative rotation from the current position you'll either need to keep track of the absolute rotation for your button and use your existing method (which would probably be faster), or concatenate the new rotation into the existing rotation. Below is the code for concatenating rotation matrices.

    I'm not up on my Obj-C (I use MonoTouch) but it would probably look something like this in C:

    image.transform = image.transform.Rotate(DEGREES_TO_RADIANS(degrees));
    

    Or this:

    image.transform = CGAffineTransformationConcat( 
        image.transform, 
        CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(degrees));
    )
    

    Feel free to edit this post to make it proper Obj-C.