Problem with QuartzCore keyword in ios

my code draws 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); } 
+4
source share
1 answer

The answer is that CoreGraphics uses a coordinate system that has a beginning in the lower left corner, which is a Postscript convention. On iOS, however, the origin is in the upper left corner.

To use CoreGraphics, you need to flip the coordinate system and shift the origin to the top of the frame.

Here's what your drawRect method looks 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); } 
+5
source

Source: https://habr.com/ru/post/1340040/


All Articles