Flipped NSString drawing in CGContext

后端 未结 2 1744
天涯浪人
天涯浪人 2020-12-17 04:32

I try to draw a string in this texture:

http://picasaweb.google.it/lh/photo/LkYWBv_S_9v2d6BAfbrhag?feat=directlink

but the green numbers seem vertical flippe

相关标签:
2条回答
  • 2020-12-17 05:14

    As describe here, the coordinate system for a context within a UIView or its layer is inverted when compared to the normal Quartz drawing space. However, when using Quartz to draw to an image, this is no longer the case. The UIStringDrawing Cocoa Touch category on NSString that gives you the -drawAtPoint:withFont: method assumes an inverted layout, and that's why you're seeing the flipped text in your image.

    One way to work around this would be to save the graphics state, apply an invert transform to the image, draw the text, and restore the old graphics state. This would look something like the following:

    CGContextSaveGState(context);
    CGContextTranslateCTM(context, 0.0f, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0f, -1.0f);
    
    [text drawAtPoint:CGPointMake(0.0f, 0.0f) withFont:font];
    
    CGContextRestoreGState(context);
    

    This is a fairly crude example, in that I believe it just draws the text at the bottom of the image, but you should be able to adjust the translation or the coordinate of the text to place it where it's needed.

    0 讨论(0)
  • 2020-12-17 05:31

    Better save the text 's matrix before draw, otherwise it will affect other text draw by CoreGraphic:

    CGContextSaveGState(ctx);
    CGAffineTransform save = CGContextGetTextMatrix(ctx);
    CGContextTranslateCTM(ctx, 0.0f, self.bounds.size.height);
    CGContextScaleCTM(ctx, 1.0f, -1.0f);
    [str drawAtPoint:point withFont:font];
    CGContextSetTextMatrix(ctx, save);
    CGContextRestoreGState(ctx);
    
    0 讨论(0)
提交回复
热议问题