3 回答

TA贡献1898条经验 获得超8个赞
Core Animation Programming Guide 的Layer Geometry and Transforms部分解释了CALayer的position和anchorPoint属性之间的关系。基本上,层的位置是根据图层的anchorPoint的位置指定的。默认情况下,图层的anchorPoint为(0.5,0.5),位于图层的中心。设置图层的位置时,您将在其超层图层的坐标系中设置图层中心的位置。
因为位置是相对于图层的anchorPoint,所以在保持相同位置的同时更改该anchorPoint会移动图层。为了防止这种移动,您需要调整图层的位置以考虑新的anchorPoint。我这样做的一种方法是抓取图层的边界,将边界的宽度和高度乘以旧的和新的anchorPoint的标准化值,取两个anchorPoints的差值,并将该差值应用于图层的位置。
您甚至可以通过使用CGPointApplyAffineTransform()UIView的CGAffineTransform以这种方式考虑轮换。

TA贡献1805条经验 获得超10个赞
我有同样的问题。Brad Larson的解决方案即使在视图旋转时也能很好地工作。这是他的解决方案翻译成代码。
-(void)setAnchorPoint:(CGPoint)anchorPoint forView:(UIView *)view
{
CGPoint newPoint = CGPointMake(view.bounds.size.width * anchorPoint.x,
view.bounds.size.height * anchorPoint.y);
CGPoint oldPoint = CGPointMake(view.bounds.size.width * view.layer.anchorPoint.x,
view.bounds.size.height * view.layer.anchorPoint.y);
newPoint = CGPointApplyAffineTransform(newPoint, view.transform);
oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform);
CGPoint position = view.layer.position;
position.x -= oldPoint.x;
position.x += newPoint.x;
position.y -= oldPoint.y;
position.y += newPoint.y;
view.layer.position = position;
view.layer.anchorPoint = anchorPoint;
}
而快速的等价物:
func setAnchorPoint(anchorPoint: CGPoint, forView view: UIView) {
var newPoint = CGPointMake(view.bounds.size.width * anchorPoint.x, view.bounds.size.height * anchorPoint.y)
var oldPoint = CGPointMake(view.bounds.size.width * view.layer.anchorPoint.x, view.bounds.size.height * view.layer.anchorPoint.y)
newPoint = CGPointApplyAffineTransform(newPoint, view.transform)
oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform)
var position = view.layer.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
view.layer.position = position
view.layer.anchorPoint = anchorPoint
}
SWIFT 4.x
func setAnchorPoint(anchorPoint: CGPoint, forView view: UIView) {
var newPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x,
y: view.bounds.size.height * anchorPoint.y)
var oldPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x,
y: view.bounds.size.height * view.layer.anchorPoint.y)
newPoint = newPoint.applying(view.transform)
oldPoint = oldPoint.applying(view.transform)
var position = view.layer.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
view.layer.position = position
view.layer.anchorPoint = anchorPoint
}
- 3 回答
- 0 关注
- 791 浏览
添加回答
举报