NSString drawInRect 导致 CGContextShowTextAtPoint 错误显示文本
我在 iOS 应用程序中使用 CGContextRef 来创建 PDF,以及我创建的一些实用方法来绘制线条、文本、图像等项目。
我有以下方法用于绘制多行文本字符串到 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 systemFontOfSize:fontSize]];
CGContextRestoreGState(pdfContext);
UIGraphicsPopContext();
}
此代码对于绘制文本块效果很好,但如果我在执行此代码后尝试使用 CGContextShowTextAtPoint 绘制任何其他文本,则文本会太大且上下颠倒。
如果我在方法末尾添加这一行,大小会恢复正常,但文本仍然颠倒:
CGContextSetTextMatrix(pdfContext, CGAffineTransformMake(1.0,0.0, 0.0, -1.0, 0.0, 0.0));
我一定在这里遗漏了一些东西,看起来原始代码应该保存和恢复足够的上下文状态画画继续就好了。有什么提示或建议吗?
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 systemFontOfSize: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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一个小错字吗?在你的代码中,尝试:
注意 -1.0 现在是 1.0
There is a small typo? in your code, try:
note the -1.0 is now a 1.0