Search code examples
objective-cioscore-graphicsquartz-graphicsdrawrect

getting the text up-side down in core graphic


I am drawing a text in core graphic by following

- (void)drawRect:(CGRect)rect {
    CGContextTranslateCTM(context, 20, 150);
    CGContextScaleCTM(context, 1, 1);

    // Draw the text using the MyDrawText function
    myDrawText(context, viewBounds);

}
void myDrawText (CGContextRef myContext, CGRect contextRect) 
{
    CGFloat w, h;
    w = contextRect.size.width;
    h = contextRect.size.height;

    CGAffineTransform myTextTransform;
    CGContextSelectFont (myContext, 
                         "Helvetica-Bold",
                         h/12,
                         kCGEncodingMacRoman);
    CGContextSetCharacterSpacing (myContext, .5); 
    CGContextSetTextDrawingMode (myContext, kCGTextFill); 

    CGContextSetRGBFillColor (myContext, 1, 1, 1, 1); 
    myTextTransform =  CGAffineTransformMakeRotation  (0); 
    CGContextSetTextMatrix (myContext, myTextTransform); 
    CGContextShowTextAtPoint (myContext, 115, 0, "Successful", 10); 
}

After running it I am getting the text is in up-side down like below enter image description here

Why the text is up side down after the drawing

Please advice me on this issue.


Solution

  • this is the way to flip it. Just add 2 lines to your drawRect

    - (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 20, 150);
    CGContextScaleCTM(context, 1, 1);
    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, 0);
    CGContextConcatCTM(context, flipVertical);
    
    // Draw the text using the MyDrawText function
    myDrawText(context, self.bounds);
    
    }