How to understand the math behind the CTM(current transformation matrix)?

187 Views Asked by At

When I written some test code about modifying CTM, I found it can't be explain with The Math Behind the Matrices in Quartz 2D Programming Guide. The test code is as follow:

// {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);

The output: 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]

First, let's focus on UIKit CTM transforms to Quartz CTM, we use array express matrix, on line 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]

then

[1, 0, 0, 0, 1, 0, tx1, ty1, 1] = [1, 0, 0, 0, 1, 0, -1136, 1]

so in this case CGContextTranslateCTM(ctx, 0, CGRectGetHeight(rect)); equal to [1, 0, 0, 0, 1, 0, -1136, 1], Question 1: Where is minus sign come from?

On line 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]

then

[sx1, 0, 0, 0, sy1, 0, 0, 0, 1] = [1, 0, 0, 0, -1, 0, 0, 0, 1]

so CGContextScaleCTM(ctx, 1, -1); equal to [1, 0, 0, 0, -1, 0, 0, 0, 1], this result is the same as theory value.

On line 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]

then

[1, 0, 0, 0, 1, 0, tx2, ty2, 1] = [2, 0, 0, 0, 2, 0, 0, 1136, 1]

this result also the same as theory value.

On line 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]

then [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; but

2*sy2 = -2 (1)
1136*sy2 = 1136 (2)

In equation (1) sy2 = -1, but in equation (2) sy2 = 1, So Question 2: Why this happened? How to explain this case?

0

There are 0 best solutions below