CGAffineTransformMakeRotation 如何围绕外部点旋转?

5
有没有一种方法可以使用CGAffineTranformMAkeRotation围绕外部点旋转UIImage?非常感谢!
4个回答

20

这里有一个函数,它使用与CoreGraphics CGAffineTransform API相同的格式。

这个函数正好按照其他“RotateAt()”API应该工作的方式工作。

该操作表示等价于以下规范:translate(pt.x,pt.y); rotate(angle); translate(-pt.x,-pt.y);

CGAffineTransform CGAffineTransformMakeRotationAt(CGFloat angle, CGPoint pt){
    const CGFloat fx = pt.x, fy = pt.y, fcos = cos(angle), fsin = sin(angle);
    return CGAffineTransformMake(fcos, fsin, -fsin, fcos, fx - fx * fcos + fy * fsin, fy - fx * fsin - fy * fcos);
}

就像使用CGAffineTransformMakeRotation()一样,这里的角度是用弧度而不是度来表示的。


1
我假设pt是一个中心? - pronebird
为什么不能只使用 var t = CGAffineTransformMakeTranslation(-pt.x,-pt.y) 进行平移,然后使用 t = CGAffineTransformRotate(t,angel) 进行旋转,最后再使用 var t = CGAffineTransformTranslate(t,pt.x,pt.y) 进行平移回去呢? - Adam
1
@Adam 那是你需要做的三件事情。我的答案是一个调用可以完成所有三个任务。非常优化。请重新阅读我的答案,特别是代码前的第三行。 - Andy

2

将图像视图的图层锚点设置为(0,0)和(1,1)之外的其他位置,例如view.layer.anchorPoint = CGPointMake(2, 2)。


如果你选择这个选项,请记住两件事:a)这将完全改变视图的绘制位置,而不仅仅是转换;b)anchorPoint的x和y值是相对于视图大小的倍数,我认为它们不在主视图坐标系中。 - mjisrawi

2
我是这样解决的: 我将要旋转的UIImage放入另一个视图中。 该视图比图像视图更大,因此视图的中心点是uiimage视图的外部点,因此我旋转了该视图....

1

我刚试了一下。类似这样的代码应该能给你想要的结果...

- (void)rotateView:(UIView *)view aroundPoint:(CGPoint)point withAngle:(double)angle{
    //save original view center
    CGPoint originalCenter = view.center; 

    //set center of view to center of rotation
    [view setCenter:point];

    //apply a translation to bring the view back to its original point
    view.transform = CGAffineTransformMakeTranslation(originalCenter.x, originalCenter.y);

    //multiply the view's existing rotation matrix (the translation) by a rotation and apply it to the view
    //thereby making it rotate around the external point
    view.transform = CGAffineTransformConcat(view.transform, CGAffineTransformMakeRotation(angle));
}

只是想解释一下我的推理...

我们基本上正在做的是将视图在旋转点处进行物理移动,然后应用平移来使其看起来像停留在原始点。然后,如果我们将旋转乘以视图的新平移,我们实际上旋转了整个视图及其坐标系,因此它看起来像是围绕给定点旋转。我希望我解释得清楚。:| 如果没有,我建议在线查找变换矩阵,也许您可以找到更好的解释方式!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接