getting the text up-side down in core graphic

99封情书 提交于 2020-01-16 19:57:27

问题


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

Why the text is up side down after the drawing

Please advice me on this issue.


回答1:


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

}



回答2:


CGContextSetTextMatrix (myContext, myTextTransform);

You need to change this line so that instead of being identity, you scale it -1 vertically and offset it vertically by its height.

EDIT: Sorry, not that line, you need to flip the graphics context, and simply change that line to be CGAffineTransformIdentity. Any tutorial on Core Text will have the lines you need to draw text the right way.



来源:https://stackoverflow.com/questions/13003239/getting-the-text-up-side-down-in-core-graphic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!