• Create Account

## Rotating an object within a box

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

2 replies to this topic

### #1GaMEFRo  Members

Posted 03 October 2012 - 06:22 AM

I'm developing a game for the iPhone, and I have a situation where I have a graphic that the user can drag around the screen and there are some buttons the user can push to both rotate it and enlarge it. The graphic is located within a UIView, which is just a rectangular shape that fits tightly around it.

The thing I'm having trouble with is rotating the graphic, and then translating it so it fits within the UIView correctly. When the user pushes the button to rotate, the first thing I'm doing is calculating the correct size the UIView frame needs to be to fit the rotated object. Then I do the following:

- (CGAffineTransform) transform
{
CGAffineTransform transform = CGAffineTransformIdentity;
transform = CGAffineTransformRotate(transform, (M_PI * self.graphicRotationAngle) / 180);
transform = CGAffineTransformScale(transform, self.graphicSize.width / self.graphic.size.width, self.graphicSize.height / self.graphic.size.height);
transform = CGAffineTransformTranslate(transform, self.graphicSize.width - self.frame.size.width, self.graphicSize.height - self.frame.size.height);

return transform;
}


It makes sense to me that in order to translate the object back to the upper left corner (0,0), i have to subtract the new size of the frame width and height value, minus the non rotated images width and height, and that should give me the translation I need. Yet it's not working, do I have the correct order of operations?

Any help would be appreciated.

Edited by GaMEFRo, 04 October 2012 - 05:56 AM.

### #2GaMEFRo  Members

Posted 04 October 2012 - 05:52 AM

Bump - I made the post a lot more concise and a little more descriptive. Any help would be appreciated, thanks.

### #3FriesBoury  Members

Posted 04 October 2012 - 01:19 PM

I'm not sure how it works in the environment you are programming in, but almost always, an image gets drawn beginning from the top left corner.
Therefore the first transformation you do, will use this corner as an "anchorpoint".

Before you do the rotation, try to move your image so the center of your image matches the (0,0) coordinates. Not the top left corner.

so your transformations should be:
- 1: translation with offset(-imageWidth/2, -imageHeight/2)
- 2 and 3: rotation and scale (both don't affect position of anchorpoint, so order doesn't really matter here)
- 4: translation to match image center with frame center (frameWidth/2, frameHeight/2)

I hope this was useful to you.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.