简体   繁体   中英

Animation moves image

I am trying to create my first iPhone application. The application is simply a arrow pointing at north. I have so far added a image of a arrow, and created a animation via the following code:

- (void)setDirection:(float)degree {
        float rad = M_PI * (float)degree / 180.0;
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:10];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
         //[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        DirectionArrow.transform = CGAffineTransformMakeRotation(rad);
        [UIView commitAnimations];
    }

My problem is that the arrow "moves" before it rotates, each time I call the method. I have tried varius things to center the rotation angle, but without any luck.

I want the arrow (image) to rotate around its own axis.

This is because your view is rotating around (0, 0) , which is the top-left corner of your view. You'd want to rotate around the center of the arrow instead.

To do so, you'll have to build a transform that does the following:

  1. Translates the arrow such that it's center is at (0, 0) .
  2. Rotates the view in rad degrees.
  3. Translates the arrow back (the inverse transform of (1)).

It should be something like (up to flip of t1 and t3):

CGFloat h = view.bounds.size.height;
CGFloat w = view.bounds.size.width;
CGAffineTransform t1 = CGAffineTransformMakeTranslation(-w/2, -h/2);
CGAffineTransform t2 = CGAffineTransformMakeRotation(rad);
CGAffineTransform t3 = CGAffineTransformMakeTranslation(w/2, h/2);
CGAffineTransform t = CGAffineTransformConcat(CGAffineTransformConcat(t3, t2), t1);
DirectionArrow.transform = t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM