ios中的QuartzCore drawtext问题

Arc*_*ian 4 objective-c quartz-graphics ipad ios

我的代码颠倒了这个文字.为什么?

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

}
Run Code Online (Sandbox Code Playgroud)

Gor*_*tch 5

答案是CoreGraphics使用一个坐标系统,其原点位于左下角,即Postscript约定.然而,iOS上的原点位于左上角.

要使用CoreGraphics,您必须翻转坐标系并将原点移动到框架的上边缘.

以下是drawRect方法的外观.

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

}
Run Code Online (Sandbox Code Playgroud)