Ios 如何正确组合CGAffineTransform矩阵?

Ios 如何正确组合CGAffineTransform矩阵?,ios,swift,matrix,cgaffinetransform,Ios,Swift,Matrix,Cgaffinetransform,应缩放和变换图像 根据变换矩阵的组成方式,我会得到不同的结果: // A) This produces the desired result, scales the image and translates the image independently from each other let transform = CGAffineTransform(translationX: translation.x, y: translation.y).scaledBy(x: scale.width,

应缩放和变换图像

根据变换矩阵的组成方式,我会得到不同的结果:

// A) This produces the desired result, scales the image and translates the image independently from each other
let transform = CGAffineTransform(translationX: translation.x, y: translation.y).scaledBy(x: scale.width, y: scale.height)

// B) This also produces the desired result
let scaleTransform = CGAffineTransform(scaleX: scale.width, y: scale.height)
let translateTransform = CGAffineTransform(translationX: translation.x, y: translation.y)
let transform = scaleTransform.concatenating(translateTransform)

// C) This does not produce the desired result, it also scales the translation, so a 10x scale results in a 10x translation
let transform = CGAffineTransform(scaleX: scale.width, y: scale.height).translatedBy(x: translation.x, y: translation.y)

// Transform image
image = image.transformed(by: transform)

如果
.concatenating
表示相乘,
.scaledBy
。translatedBy
表示将两个矩阵相加,既然矩阵顺序在相加时并不重要,为什么A和C不能产生相同的结果?

缩放矩阵和平移矩阵的乘法和加法具有相同的结果,这是巧合

在一般情况下,
scaledBy
translatedBy
并不意味着相加,它们是连接两个变换的缩写,这是矩阵乘法。矩阵乘法仅适用于对角矩阵(对角线上只有非零值的矩阵),因此
S*T
通常与
T*S
不同

查找
$(xcrun--show sdk path)/System/Library/Frameworks/CoreGraphics.framework/Headers/CGAffineTransform.h
,了解每个函数的作用:

  • CGAffineTransformTranslate
    :t'=[1 0 0 1 tx ty]*t
  • CGAffineTransformScale
    :t'=[sx 0 sy 0 0]*t
  • CGAffineTransformRotate
    :t'=[cos(角度)sin(角度)-sin(角度)cos(角度)0]*t
  • cGraffineTransformConcat
    :t'=t1*t2

这意味着当您使用
cGraffeTransformConcat
时,
t1
必须是您正在应用的转换,而
t2
必须是您正在转换的矩阵。换句话说,
scale.translatedBy
相当于
concat(translation,scale)
,而不是
concat(scale,translation)
。当使用
串联
作为一种方法时,由于其数学定义,这会使运算向后看。

除了@zneak所说的,矩阵运算的顺序很重要,因为矩阵乘法(串联)是不可交换的。那是A*B≠ B*A一般来说


因为顺序在C中是颠倒的,所以产生了不同的结果。

如果
scaledBy
translatedBy
也是乘法,那么为什么B和C不能产生相同的结果呢?两者都是
scale matrix
x
translation matrix
@Manuel,
a.连接(b)
bxa
func连接(ut2:cgafinetransform)->cgafinetransform
的方法描述是:
t'=t1*t2
。这不是意味着连接(b)是
a x b
?@Manuel,你说得对,带交换参数的是其他变换。见最新编辑。@Manuel,我不是那个意思。X.concat(Y)是X X Y,但X.scale(Y)是Y X X,X.translate(Y)也是Y X X。示例A和B是相同的,C是不同的。