当我写一些关于修改CTM的测试代码时,我发现它无法用Quartz 2D Programming Guide中的矩阵后面的数学来解释。测试代码如下:
// {a, b, c, d, tx, ty}
NSLog(@"UIKit CTM:%@\n", NSStringFromCGAffineTransform(CGContextGetCTM(ctx)));
CGContextSaveGState(ctx);
CGContextTranslateCTM(ctx, 0, CGRectGetHeight(rect));// 1
NSLog(@"Quartz part 1 CTM:%@\n", NSStringFromCGAffineTransform(CGContextGetCTM(ctx)));
CGContextScaleCTM(ctx, 1, -1);// 2
NSLog(@"Quartz CTM:%@\n", NSStringFromCGAffineTransform(CGContextGetCTM(ctx)));
CGContextTranslateCTM(ctx, 0, CGRectGetHeight(rect)); // 3
NSLog(@"UIKit part 1 CTM:%@\n", NSStringFromCGAffineTransform(CGContextGetCTM(ctx)));
CGContextScaleCTM(ctx, 1, -1);// 4
NSLog(@"UIKit part 2 CTM:%@\n", NSStringFromCGAffineTransform(CGContextGetCTM(ctx)));
CGContextRestoreGState(ctx);
输出:
2017-09-29 09:51:27.166 QuartzDemo[53287:31120880] UIKit CTM:[2, 0, 0, -2, 0, 1136]
2017-09-29 09:51:27.167 QuartzDemo[53287:31120880] Quartz part 1 CTM:[2, 0, 0, -2, 0, 0]
2017-09-29 09:51:27.167 QuartzDemo[53287:31120880] Quartz CTM:[2, 0, -0, 2, 0, 0]
2017-09-29 09:51:27.167 QuartzDemo[53287:31120880] UIKit part 1 CTM:[2, 0, -0, 2, 0, 1136]
2017-09-29 09:51:27.167 QuartzDemo[53287:31120880] UIKit part 2 CTM:[2, 0, 0, -2, 0, 1136]
首先,让我们关注UIKit CTM转换为Quartz CTM,我们在第1行使用数组表达矩阵:
[2,0,0,0,-2,0,0,1136,1] x [1,0,0,0,1,0,tx1,ty1,1] = [2,0,0] ,0,-2,0,0,0,1]
然后
[1,0,0,0,1,0,tx1,ty1,1] = [1,0,0,0,1,0,-1136,1]
所以在这种情况下CGContextTranslateCTM(ctx, 0, CGRectGetHeight(rect));
等于[1,0,0,0,1,0,-1136,1],问题1:减号来自哪里?
第2行:
[2,0,0,0,-2,0,0,0,1] x [sx1,0,0,0,sy1,0,0,0,1] = [2,0,0] ,-0,2,0,0,0,1]
然后
[sx1,0,0,0,sy1,0,0,0,1] = [1,0,0,0,-1,0,0,0,1]
所以CGContextScaleCTM(ctx, 1, -1);
等于[1,0,0,0,-1,0,0,0,1],这个结果与理论值相同。
第3行:
[2,0,0,-0,2,0,0,0,1] x [1,0,0,0,1,0,tx2,ty2,1] = [2,0,0] ,-0,2,0,0,1136,1]
然后
[1,0,0,0,1,0,tx2,ty2,1] = [2,0,0,0,2,0,0,1136,1]
这个结果也与理论值相同。
第4行:
[2,0,0,0,2,0,0,1136,1] x [sx2,0,0,0,sy2,0,0,0,1] = [2 * sx2,0, 0,0,2 * sy2,0,0,1136 * sy2,1]
然后 [2 * sx2,0,0,0,2 * sy2,0,0,1136 * sy2,1] = [2,0,0,0,-2,0,0,1136,1]
2 * sx2 = 2 => sx2 = 1;但是
2 * sy2 = -2(1)
1136 * sy2 = 1136(2)
在等式(1)中sy2 = -1,但在等式(2)中sy2 = 1,所以问题2:为什么会发生这种情况?如何解释这个案子?