Scale UIView with the top center as the anchor point?

Alistair Holt picture Alistair Holt · Dec 23, 2012 · Viewed 22k times · Source

I'm scaling a UIView with CGAffineTransformMakeScale but I want to keep it anchored to it's current top center point as it's scaled.

I've looked into setting view.layer.anchorPoint but I believe I need to use this in conjunction with setting view.layer.position to account for the change in the anchor point.

If anyone could point me in the right direction I'd be very grateful!

Answer

rob mayoff picture rob mayoff · Dec 23, 2012

Take a look at my answer here to understand why your view is moving when you change the anchor point: https://stackoverflow.com/a/12208587/77567

So, start with your view's transform set to identity. When the view is untransformed, find the center of its top edge:

CGRect frame = view.frame;
CGPoint topCenter = CGPointMake(CGRectGetMidX(frame), CGRectGetMinY(frame));

Then the anchor point to the middle of the top edge:

view.layer.anchorPoint = CGPointMake(0.5, 0);

Now the layer's position (or the view's center) is the position of the center of the layer's top edge. If you stop here, the layer will move so that the center of its top edge is where its true center was before changing the anchor point. So change the layer's position to the center of its top edge from a moment ago:

view.layer.position = topCenter;

Now the layer stays in the same place on screen, but its anchor point is the center of its top edge, so scales and rotations will leave that point fixed.