更改我的 CALayer 的锚点会移动视图 [英] Changing my CALayer's anchorPoint moves the view

查看:25
本文介绍了更改我的 CALayer 的锚点会移动视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改 anchorPoint,但将视图保持在同一位置.我已经尝试过 NSLog-ing self.layer.positionself.center 并且它们都保持不变,无论锚点如何变化.然而我的观点移动了!

I want to alter the anchorPoint, but keep the view in the same place. I've tried NSLog-ing self.layer.position and self.center and they both stay the same regardless of changes to the anchorPoint. Yet my view moves!

有关如何执行此操作的任何提示?

Any tips on how to do this?

self.layer.anchorPoint = CGPointMake(0.5, 0.5);
NSLog(@"center point: %f %f", self.layer.position.x, self.layer.position.y);
self.layer.anchorPoint = CGPointMake(1, 1);
NSLog(@"center point: %f %f", self.layer.position.x, self.layer.position.y);

输出为:

2009-12-27 20:43:24.161 Type[11289:207] center point: 272.500000 242.500000
2009-12-27 20:43:24.162 Type[11289:207] center point: 272.500000 242.500000

推荐答案

Layer Geometry and Transforms 部分解释了CALayer 的位置和anchorPoint 属性之间的关系.基本上,图层的位置是根据图层的锚点的位置指定的.默认情况下,图层的锚点为 (0.5, 0.5),位于图层的中心.当您设置图层的位置时,您就是在设置图层中心在其超图层坐标系中的位置.

The Layer Geometry and Transforms section of the Core Animation Programming Guide explains the relationship between a CALayer's position and anchorPoint properties. Basically, the position of a layer is specified in terms of the location of the layer's anchorPoint. By default, a layer's anchorPoint is (0.5, 0.5), which lies at the center of the layer. When you set the position of the layer, you are then setting the location of the center of the layer in its superlayer's coordinate system.

因为位置是相对于图层的锚点,在保持相同位置的同时改变锚点会移动图层.为了防止这种移动,您需要调整图层的位置以考虑新的锚点.我这样做的一种方法是获取图层的边界,将边界的宽度和高度乘以新旧锚点的归一化值,取两个锚点的差值,并将该差值应用于图层的位置.

Because the position is relative to the anchorPoint of the layer, changing that anchorPoint while maintaining the same position moves the layer. In order to prevent this movement, you would need to adjust the layer's position to account for the new anchorPoint. One way I've done this is to grab the layer's bounds, multiply the bounds' width and height by the old and new anchorPoint's normalized values, take the difference of the two anchorPoints, and apply that difference to the position of the layer.

您甚至可以通过将 CGPointApplyAffineTransform() 与 UIView 的 CGAffineTransform 结合使用来以这种方式计算旋转.

You might even be able to account for rotation this way by using CGPointApplyAffineTransform() with your UIView's CGAffineTransform.

这篇关于更改我的 CALayer 的锚点会移动视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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