CGAffineTransform:如何计算乘法CGAffineTransform?

CGAffineTransform: How to calculate multiply CGAffineTransform?

我需要将视图从原点 (250, 250) 转换为原点 (352, 315),并且 width/height 从 (100.0, 100.0) 更改为 (68, 68)。 我知道我可以将几个 CGAffineTransform 函数组合在一起,例如缩放、旋转、平移。 但我不知道如何计算这些转换的顺序,以及它们的确切参数。 我已经尝试了几次,但无法将视图移动到正确的位置。

有人可以帮忙吗?

struct CGAffineTransform {
  CGFloat a, b, c, d;
  CGFloat tx, ty;
};

可以通过这个获取参数struct.And transforms always override,也就是说不会叠加,注意这个

对这些矩阵变换的幕后发生的事情有一点了解总是好的。

Apple 文档有一个关于转换的 great documentation,所以让我们使用它。


一个翻译矩阵看起来像:

|  1   0   0  |
|  0   1   0  |
|  tx  ty  1  |

其中 (tx, ty) 是您的翻译向量。


一个缩放矩阵看起来像:

|  sx  0   0  |
|  0   sy  0  |
|  0   0   1  |

其中 sxsy 是 X 轴和 Y 轴的比例因子。


您想使用 CGAffineTransformConcat 连接这些矩阵,但根据 its doc

Note that matrix operations are not commutative—the order in which you concatenate matrices is important. That is, the result of multiplying matrix t1 by matrix t2 does not necessarily equal the result of multiplying matrix t2 by matrix t1.

您必须在缩放之前平移您的视图,否则您的平移矢量将根据 sxsy 系数进行缩放。

让我们简单地展示一下:

let scaleMatrix = CGAffineTransformMakeScale(0.68, 0.68)
let translateMatrix = CGAffineTransformMakeTranslation(102, 65)

let translateThenScaleMatrix = CGAffineTransformConcat(scaleMatrix, translateMatrix)
NSLog("translateThenScaleMatrix : \(translateThenScaleMatrix)")
// outputs : CGAffineTransform(a: 0.68, b: 0.0, c: 0.0, d: 0.68, tx: 102.0, ty: 65.0)
// the translation is the same

let scaleThenTranslateMatrix = CGAffineTransformConcat(translateMatrix, scaleMatrix)
NSLog("scaleThenTranslateMatrix : \(scaleThenTranslateMatrix)")
// outputs : CGAffineTransform(a: 0.68, b: 0.0, c: 0.0, d: 0.68, tx: 69.36, ty: 44.2)
// the translation has been scaled too

让我们用数学来证明它。请注意,当您执行操作 A 然后执行操作 B 时,相关矩阵是通过执行 matB*matA 计算的,第一个操作在右侧。由于矩阵的乘法不可交换,因此很重要。

// Translate then  scaling :
|  sx  0   0  |   |  1   0   0  |   |    sx   0    0 |
|  0   sy  0  | . |  0   1   0  | = |    0    sy   0 |
|  0   0   1  |   |  tx  ty  1  |   |    tx   ty   1 |
// The resulting matrix has the same value for translation

// Scaling then translation :
|  1   0   0  |   |  sx  0   0  |   |    sx     0      0 |
|  0   1   0  | . |  0   sy  0  | = |    0      sy     0 |
|  tx  ty  1  |   |  0   0   1  |   |  sx.tx   sy.ty   1 |
// The translation values are affected by scaling coefficient