Rotating an UIView around an arbitrary point

Developing on iOS often brings joy thanks to default behaviours and design choices made by the Apple designers, but you can get many headaches too when trying to step off the beaten path.
Fortunately this time the solution is easy and straightforward and the headaches are saved for other more consistent problems. 🙂

Recently I had to let a user rotate a View on an iPhone app using his fingers, but when tested, the view rotated around its center.

I wanted it to mimic the real world, where if you do it on a piece of paper lying on a table, it usually spins around your two fingers.

To rotate a view, we need to apply to it an affine transformation, and looking at the UIView Class Reference we read:
“The origin of the transform is the value of the center property, or the layer’s anchorPoint property if it was changed.”

So the anchorPoint of the view’s layer is the point around which transformations (in this case a rotation) are applied. If we change it accordingly to a middle point between our two fingers touches we are set and running!

Unfortunately its coordinates are normalised to the UIView boundaries, ranging from 0 to 1, with the center represented by 0.5, 0.5.

The trick will be done by this little snippet of code:

CGPoint firstTouch  = [(UIRotationGestureRecognizer*)sender locationOfTouch:0 inView:self];
CGPoint secondTouch = [(UIRotationGestureRecognizer*)sender locationOfTouch:1 inView:self];

self.layer.anchorPoint = CGPointMake(((firstTouch.x + secondTouch.x)/2)/self.bounds.size.width, ((firstTouch.y + secondTouch.y)/2)/self.bounds.size.height);

With self being our UIView class. If you want to try a demo, you can clone our simple demo app on Github.

Leave a Reply

wpDiscuz