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!
It's an old question, but I faced the same problem and took me a lot of time to get to the desired behavior, expanding a little bit the answer from @Rob Mayoff (I found the solution thanks to his explanation). I had to show a floating-view scaling from a point touched by the user. Depending on screen coords, It could scale down, right, left, up or from the center.
The first thing to do is to set the center of our floating view in the touch point (It has to be the center, 'cause as Rob explanation):
The next issue is to setup the anchor point of the layer, depending on what we want to do (I measured the point relative to the screen frame, and determined where to scale it):
Now, all it's easy. Depending on the effect you want to give to the animation (The idea was a bouncing scaling from 0 to 100%):
That's it. As you can see, the main thing is to setup correctly the view's position and anchor point. Then, it's all piece of cake! Regards, and let the code be with you!
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:
Then the anchor point to the middle of the top edge:
Now the layer's
position
(or the view'scenter
) 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'sposition
to the center of its top edge from a moment ago: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.
Swift 4.2
Scaling an UIView with a specific anchor point while avoiding misplacement:
So to shrink a view to half of its size with its top center as anchor point: