CALayer的anchorPoint 与position

2021-9-27 更新

最近看到个面试题 anchorPoint 和 position的区别
想起来自己之前搞过这个文章,进来一看,看不明白了
之前的写得太糟糕了。
再捋一遍:

  • position 是相对于父layer来说
  • anchor point 是相对于自身来说
  • 并且二者应该是相等的
  • 初始条件下,锚点为自身中心
    基于第三条原则,当你修改锚点时,你的position就会自动变化,就导致你的frame就变了。
    结论:要进行不绕中心点旋转操作时,要先确定锚点,再确定frame。
//The position in the superlayer that the anchor point of the layer's bounds rect is aligned to. Defaults to the zero point. Animatable.
//大概意思是 这个属性是相对于父layer,并且等于本layer中的anchor point
@property CGPoint position;
/* Defines the anchor point of the layer's bounds rect, as a point in
 * normalized layer coordinates - '(0, 0)' is the bottom left corner of
 * the bounds rect, '(1, 1)' is the top right corner. Defaults to
 * '(0.5, 0.5)', i.e. the center of the bounds rect. Animatable. */
//定义锚点在本layer的bounds中
@property CGPoint anchorPoint;

对于旋转问题来讲

问题

项目中遇到了一个“bug”,我做了一个动画,旋转一个指针,但不是围绕中心来转。而是像仪表盘指针一样的转。所以我首次尝试了改变了指针的锚点anchor point ,但是实际情况并不正确,指针的frame莫名其妙的被改变了,打断点查看,在我设置锚点之后,指针的frame就发生变化了。于是找到了这篇深度好文
个人比较笨,反复体会两三次,才知道其中的奥义。也顺便想起来培训的时候,老师也曾带我们做过此类测试。老师此刻可能在骂我。

总结

父视图 + 子视图 的 样式。
一旦子视图在父视图中位置(frame)放好。子视图的position随之固定(0.5, 0.5),子视图旋转只能在这个位置,任凭你的anchor point 怎么变化,你偷逃不过父视图的手掌心(就是绕着最开始你在父视图的位置的中心点来旋转)。
再者这个anchor point 当他变化的时候,视图确实是按照anchor point来旋转的。但同时也是父视图的position。这是咋回事?子视图又是按照自己的anchor point 来转,又是父视图的position。到底是咋呢?确实如此,此时,父视图的position 与 子视图的anchor point 已经重合。为了保持这个重合,子视图的frame已经悄悄地变化了。
这才是这个“bug”的根源,原因已经找到。解决办法也是相当简单。在配置子视图位置的时候,将要变化的anchor point 与 position 重合即可。得出此时的子视图frame就可以了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容