Reputation: 4350
my code draw this text upside down. Why?
- (void)drawRect:(CGRect)rect {
// Drawing code.
CGContextRef myContext = UIGraphicsGetCurrentContext();
CGRect contextRect = self.bounds;
UIGraphicsPushContext(myContext);
CGContextSelectFont (myContext, // 3
"Courier",
24,
kCGEncodingMacRoman);
CGContextSetCharacterSpacing (myContext, 1); // 4
CGContextSetTextDrawingMode (myContext, kCGTextFillStroke); // 5
CGContextSetRGBFillColor (myContext, 0, 1, 0, 1.0); // 6
CGContextSetRGBStrokeColor (myContext, 1.0, 1.0, 1, 1); // 7
CGContextShowTextAtPoint (myContext, 100, 50, "Quartz 2D", 9);
}
Upvotes: 4
Views: 3729
Reputation: 5057
The answer is that CoreGraphics uses a coordinate system that has its origin in the lower left corner which is the Postscript convention. On iOS however the origin in in the upper left corner.
To use CoreGraphics you have to flip the coordinate system and shift the origin to the upper edge of the frame.
Here is how your drawRect method should look like.
- (void)drawRect:(CGRect)rect {
// Drawing code.
CGContextRef myContext = UIGraphicsGetCurrentContext();
CGRect contextRect = self.bounds;
// flip transform used to transform the coordinate system from origin
// top left corner to bottom right corner and inverting the y-axis
CGAffineTransform flipTransform = CGAffineTransformConcat(CGAffineTransformMakeTranslation(0.f, contextRect.size.height),
CGAffineTransformMakeScale(1.f, -1.f));
CGContextConcatCTM(myContext, flipTransform);
UIGraphicsPushContext(myContext);
CGContextSelectFont (myContext, // 3
"Courier",
24,
kCGEncodingMacRoman);
CGContextSetCharacterSpacing (myContext, 1); // 4
CGContextSetTextDrawingMode (myContext, kCGTextFillStroke); // 5
CGContextSetRGBFillColor (myContext, 0, 1, 0, 1.0); // 6
CGContextSetRGBStrokeColor (myContext, 1.0, 1.0, 1, 1); // 7
CGContextShowTextAtPoint (myContext, 100, 50, "Quartz 2D", 9);
}
Upvotes: 5