我需要从原点(250,250)到原点(352,315)的变换视图,以及宽度/高度从(100.0,100.0)到(68,68)的变化。我知道我可以把几个CGAffineTransform函数组合在一起,比如缩放,旋转,平移。但我不知道如何计算这些转换的顺序,以及它们的确切参数。我试过几次,但无法将视图移到正确的位置。
有人能帮忙吗?
发布于 2016-02-16 10:39:37
在这些矩阵转换中,稍微了解一下幕后发生的事情总是很好的。
Apple有一个关于转换的伟大的文献,所以让我们使用它。
翻译矩阵如下所示:
| 1 0 0 |
| 0 1 0 |
| tx ty 1 |其中(tx, ty)是你的翻译向量。
缩放矩阵如下所示:
| sx 0 0 |
| 0 sy 0 |
| 0 0 1 |其中sx和sy是X和Y轴的标度因子。
您希望使用CGAffineTransformConcat连接这些矩阵,但根据它的医生:
注意,矩阵运算不是可交换的--连接矩阵的顺序很重要。即矩阵t1乘矩阵t2的结果不一定等于矩阵t2乘矩阵t1的结果。
你必须在缩放之前转换你的视图,否则你的翻译向量将根据sx和sy系数进行缩放。
让我们简单地展示一下:
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发布于 2016-02-16 10:23:50
struct CGAffineTransform {
CGFloat a, b, c, d;
CGFloat tx, ty;
};您可以通过这个struct.And转换获得参数,总是覆盖,换句话说,它们不会叠加,注意这一点。
https://stackoverflow.com/questions/35429611
复制相似问题