Wednesday, June 09, 2010

iPhone dev Stupidity 124: Rotating view around arbitrary point th

From here:

"I have a UIImageView that I want to rotate around a given point. By default, the layer will rotate around the center of the UIImageView. Trying to change this anchor point involves a bit of work, either move at the beginning and reposition all the view elements, or translating the view, rotating, and translating back. The last option works fine, unless you are trying to use core animation to smoothly rotate the view.

I found out a much easier solution to the whole problem. You could call it a workaround, but it works well without disturbing the view you want rotated.

Basically, you create a new UIView. Place the center point where you want the rotation to occur. Change the size of the view so that the view you want rotated will fit inside. Make your view (you want rotated) a subview of the new view. Now, just rotate the new view, and your subview will be rotated correctly.

Example: lets say we have a UIImageView that is 320x480 (the size of the whole iPhone screen). We want it to rotate from the bottom center instead of its middle. Create a new UIView that is 0,0,320,960. This is basically double the height of the screen, positioned so the bottom half is off the screen, which places the center point right where we want it. Now place your UIImageView inside the new UIView in the top half (visible on the screen.) Now when you rotate the UIView, it will pivot on the bottom center of the screen, and your UIImageView will rotate along with it, as expected."

Instead of adding a parent view, you can also adjust the size of the view itself if feasible.

No comments: