Why is my text flipped when using CGContextShowAtPoint?

I am writing a simple practice. However, my text flips upside down when I try to use CGContext to put some string in a UIView, I wonder why and how to change it to the correct format.

Here is my code in drawRect

char *string = "TEST"; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextBeginPath(context); CGContextSelectFont (context,"Helvetica-Bold",12, kCGEncodingMacRoman); CGContextShowTextAtPoint(context, 5, 5, string, strlen(string)); CGContextClosePath(context); 

Thanx for your help.

+6
objective-c iphone
source share
3 answers

CoreGraphics uses Cartesian coordinates, so you need to translate your context before making any drawing

 CGContextRef context = UIGraphicsGetCurrentContext(); // transforming context CGContextTranslateCTM(context, 0.0, rect.size.height); CGContextScaleCTM(context, 1.0, -1.0); // your drawing code 
+5
source share

Quartz2D has an inverted y axis - convenient eh? If you use the drawRect method, you can use the following to flip the text.

 CGContextTranslateCTM(context, 0.0, rect.size.height); CGContextScaleCTM(context, 1.0, -1.0); 

Another way:

 transform = CGAffineTransformMake(1.0,0.0,0.0,-1.0,0.0,0.0); CGContextSetTextMatrix(context, transform); 

Or on one line;

 CGContextSetTextMatrix(context, CGAffineTransformMake(1.0,0.0, 0.0, -1.0, 0.0, 0.0)); 
+5
source share

Use the UIKit add-ons in NSString :

 NSString *string = @"TEST"; [string drawAtPoint:CGPointMake(5, 5) withFont:[UIFont boldSystemFontOfSize:12]]; 
+2
source share

All Articles