簡體   English   中英

CGAffineTransform:如何計算乘法CGAffineTransform?

[英]CGAffineTransform: How to calculate multiply CGAffineTransform?

我需要從原點(250,250)到原點(352,315)的變換視圖,寬度/高度從(100.0,100.0)變為(68,68)。 我知道我可以將幾個CGAffineTransform函數組合在一起,例如縮放,旋轉,平移。 但我不知道如何計算這些變換的順序,以及它們的確切參數。 我已經嘗試了幾次,但無法將視圖移動到正確的位置。

有人可以幫忙嗎?

在這些矩陣變換中,對幕后發生的事情有一點了解總是很好。

Apple文檔有關於轉換的很好的文檔 ,所以讓我們使用它。


翻譯矩陣如下所示:

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

其中(tx, ty)是你的翻譯向量。


縮放矩陣如下所示:

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

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


您希望使用CGAffineTransformConcat連接這些矩陣,但根據其文檔

請注意,矩陣運算不是可交換的 - 連接矩陣的順序很重要。 也就是說,將矩陣t1乘以矩陣t2的結果不一定等於矩陣t2乘以矩陣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
struct CGAffineTransform {
  CGFloat a, b, c, d;
  CGFloat tx, ty;
};

您可以通過此結構獲取參數。轉換總是覆蓋,換句話說,它們不會疊加,請注意這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM