开发者

QuartzCore drawtext issue in ios

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

}


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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜