小编典典

为CGAffineTransformMakeRotation Swift设置旋转点

swift

我正在使用下面的代码将UIImageViews旋转到不同的角度。

self.imageOne.transform = CGAffineTransformMakeRotation(CGFloat(-rotation))
self.imageTwo.transform = CGAffineTransformMakeRotation(CGFloat(-rotation-0.1))
self.imageThree.transform = CGAffineTransformMakeRotation(CGFloat(-change+0.1))

有什么方法可以使图像从顶部而不是中间旋转?
我想避免涉及Sprite,因为我从未使用过Sprite,也不知道如何使Sprite在单个视图应用程序中工作。谢谢你的时间。


阅读 1080

收藏
2020-07-07

共1个答案

小编典典

您正在寻找的是视图图层的anchorPoint属性。此属性基本上表示在视图四处移动时使用的
句柄

它默认为视图的中心,这就是为什么总是看到视图从中间旋转的原因。

您可以使用我在此处找到的一种很棒的方法将您的视图的anchorPoint更改为顶部(使用CGPointMake(0,0.5f))

// Swift version
// Place this before you set the transform property
setAnchorPoint(CGPointMake(0, 0.5), view: imageOne)
setAnchorPoint(CGPointMake(0, 0.5), view: imageTwo)
setAnchorPoint(CGPointMake(0, 0.5), view: imageThree)

func setAnchorPoint(anchorPoint: CGPoint, 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 : CGPoint = 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;
}

这是同一代码的目标C版本

// Obj-c version
// Place this before you set the transform property
[self setAnchorPoint:CGPointMake(0, 0.5f) forView:imageOne];
[self setAnchorPoint:CGPointMake(0, 0.5f) forView:imageTwo];
[self setAnchorPoint:CGPointMake(0, 0.5f) forView:imageThree];

-(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;
}

鼓励您在了解了anchorPoint属性表示的内容后,尝试自己理解这段代码的作用。

2020-07-07