0

我有一个 CGPath,我正在尝试旋转、缩放和翻译。我还有一个“可调整大小”的 UIView,它充当用户的助手,允许他/她应用转换,所以每当这个视图的框架发生变化时,新的转换就会应用于选定的 CGPath。另外,我将变换锚点设置为左上角。它可以很好地缩放和旋转。但是,如果我设置一个不同于 0 的旋转然后缩放,则锚点不再位于左上角。看起来它在旋转过程中发生了变化,所以假设我们从 0 旋转开始,一直到 360,然后锚点设置回左上角,正如我所期望的那样。

这是我用来创建转换的代码:

CGPoint anchorPointInPixels = CGPointMake(self.boundingBox.origin.x, self.boundingBox.origin.y);

CGAffineTransform t = CGAffineTransformIdentity;
t = CGAffineTransformTranslate(t, self.translation.x + anchorPointInPixels.x, self.translation.y + anchorPointInPixels.y);
t = CGAffineTransformRotate(t, self.rotation);
t = CGAffineTransformScale(t, self.scale.x, self.scale.y);
t = CGAffineTransformTranslate(t, -anchorPointInPixels.x, -anchorPointInPixels.y);
self.transform = t;

让我稍微解释一下这段代码: 1. 路径的点在绝对坐标中 2. 边界框只计算一次,它被设置为包围路径内所有点的矩形。边界框也在绝对坐标 3 中。平移指定了与边界框原点的偏移量,因此当路径创建后,平移等于 0,并且在用户移动它之前一直保持不变

那么,如何在不影响锚点的情况下让它旋转呢?

谢谢阅读!

马里亚诺

4

1 回答 1

0

所以我能够通过连接矩阵来解决这个问题。代码如下所示:

CGPoint anchorPointForScalingInPixels = CGPointMake(origin.x + size.width * self.anchorPointForScaling.x,
                                                    origin.y + size.height * self.anchorPointForScaling.y);

CGPoint anchorPointForRotationInPixels = CGPointMake(origin.x + size.width * self.anchorPointForRotation.x,
                                                     origin.y + size.height * self.anchorPointForRotation.y);

CGAffineTransform rotation = CGAffineTransformIdentity;
rotation = CGAffineTransformTranslate(rotation, anchorPointForRotationInPixels.x, anchorPointForRotationInPixels.y);
rotation = CGAffineTransformRotate(rotation, self.rotation);
rotation = CGAffineTransformTranslate(rotation, -anchorPointForRotationInPixels.x, -anchorPointForRotationInPixels.y);

CGAffineTransform scale = CGAffineTransformIdentity;
scale = CGAffineTransformTranslate(scale, anchorPointForScalingInPixels.x, anchorPointForScalingInPixels.y);
scale = CGAffineTransformScale(scale, self.scale.x, self.scale.y);
scale = CGAffineTransformTranslate(scale, -anchorPointForScalingInPixels.x, -anchorPointForScalingInPixels.y);

CGAffineTransform translate = CGAffineTransformMakeTranslation(self.translation.x, self.translation.y);

CGAffineTransform t = CGAffineTransformConcat(rotation, CGAffineTransformConcat(scale, translate));

这样我就可以处理两个锚点,一个用于旋转,另一个用于缩放。

于 2013-02-06T23:15:17.393 回答