以顶部中心为锚点缩放UIView? [英] Scale UIView with the top center as the anchor point?

查看:171
本文介绍了以顶部中心为锚点缩放UIView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CGAffineTransformMakeScale缩放UIView,但我希望在缩放时将其锚定到当前的顶部中心点.

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.

我已经研究了设置view.layer.anchorPoint,但是我认为我需要将此设置与设置view.layer.position结合使用,以解决定位点的变化.

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!

推荐答案

在此处查看我的答案,以了解更改锚点时视图为何在移动:https://stackoverflow.com/a/12208587/77567

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);

现在,图层的position(或视图的center)是图层顶部边缘中心的位​​置.如果在此处停止,则图层将移动,以使其上边缘的中心成为更改锚点之前其真实中心的位置.因此,将图层的position更改为其顶部边缘的中心:

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.

这篇关于以顶部中心为锚点缩放UIView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆