Sign in to follow this  
GaMEFRo

Rotating an object within a box

Recommended Posts

GaMEFRo    131
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:

[CODE]
- (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;
}
[/CODE]


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

Share this post


Link to post
Share on other sites
FriesBoury    109
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 [b]center[/b] [b]of your image[/b] 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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this