views:

203

answers:

1

I have a 100x100 pixel image that I want to draw at various angles rotated around the center of the image. The following code works, but rotates around the original origo of the coordinate system (upper left hand corner) and not the translated location. Thus the image is not rotated around itself but around the upper left corner of the screen.

The following code was run in a custom view in a blank application with nothing else but this.

- (void)drawRect:(CGRect)rect {
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextTranslateCTM(context, -50, -50);
  CGContextRotateCTM (context, 0.3);
  CGContextTranslateCTM(context,768/2,1024/2);
  [image drawAtPoint:CGPointMake(0,0)];
}

I tried doing the same using CGAffineTransform, but got the same results.

+3  A: 

Rotation is always about the origin; what you need to do is not to defeat that, but to take advantage of it.

The key thing to remember here is that translation moves the origin. So, if you want to have the image centered at the center of the screen and rotate the image around that center, what you need to do is:

  1. Move the origin to the center of the screen.
  2. Rotate by the desired amount. (Imagine the extreme ends of the x axis moving as you do this; the left end tilts down, and the right end tilts up.)
  3. Move the origin “left” and “down” (both of these being along the new x and y axes) by half the size of the image.

Imagine the motion of the image on the iPad through each of these steps. Or, better yet, take a Post-It note and simulate it by hand:

  1. Start out with the note in a corner of the iPad.
  2. Move the note so that that corner of the note is in the center of the iPad.
  3. Rotate the note around that corner.
  4. Move the note “left” (relative to itself) by half its width and “down” (relative to itself) by half its height.

You'll notice that the note ends up rotated and in the center.

Peter Hosey
I had considered this, but when working it out in my mind, doing the final translation would not get me to a rotation centered around the center of the image, but following your steps works :-)
kasperjj