NSString drawInRect causes CGContextShowTextAtPoint to incorrectly display text
I am using a CGContextRef in my iOS application to create a PDF, along with some utility methods that I created to draw items such as lines, text, images, etc.
I have the following method that I used to draw a multiple line text string to the CGContextRef:
- (void)drawTextBlock:(NSString *)theText x:(CGFloat)x y:(CGFloat)y width:(CGFloat)w height:(CGFloat)h
{
if (theText == nil)
{
return;
}
UIGraphicsPushContext(pdfContext);
CGContextSaveGState(pdfContext);
CGContextTranslateCTM(pdfContext, 0.0f, PDF_HEIGHT);
CGContextScaleCTM(pdfContext, 1.0f, -1.0f);
[theText drawInRect:PDFCGRectMake(x, 11.0 - y - h, w, h) withFont:[UIFont systemFontOfS开发者_运维知识库ize:fontSize]];
CGContextRestoreGState(pdfContext);
UIGraphicsPopContext();
}
This code works fine for drawing text blocks, but if I try to draw any other text by using CGContextShowTextAtPoint after this code executes, the text comes out way too large and upside down.
If I add this line at the end of the method, the size goes back to normal, but the text is still upside down:
CGContextSetTextMatrix(pdfContext, CGAffineTransformMake(1.0,0.0, 0.0, -1.0, 0.0, 0.0));
I must be missing something here, it seems like the original code should save and restore the context state enough for the drawing to continue just fine. Any hints or suggestions?
There is a small typo? in your code, try:
CGContextSetTextMatrix(pdfContext, CGAffineTransformMake(1.0, 0.0, 0.0, 1.0, 0.0, 0.0));
note the -1.0 is now a 1.0
精彩评论