在使用NSAttributedString中的日文文本绘制到上下文后,是否有人遇到过Ucode在UIGraphicsEndPDFContext()失败?幸运的是,当我第一次用日语测试我的代码时,我的iPhone处于脱机状态且运行正常。但是,很久以后,当我在模拟器中运行相同的代码时,它失败了,我花了很多时间来尝试调试它。当硬连线到Mac时,尝试从iPhone或iPad上的Xcode运行它时也会失败。似乎试图以这种方式从日语中运行Xcode就是问题所在。 Mac被设置为英语。
以下是我用于绘图的方法。它紧密地基于Erica Sadun在她的书“iOS 5 Developer's Cookbook”中发表的例子,这对我来说是一本很好的阅读。它位于UIGraphicsBeginPDFContextToData()和UIGraphicsBeginPDFPageWithInfo()序列之后,并且在UIGraphicsEndPDFContext()调用之前,所有这些都在英语中正常工作。我不一定需要解决这个问题。我只是想提醒别人,以便他们可以避免我花两天时间试图解决这个问题。
- (void)drawText:(NSAttributedString *)textToDraw inFrame:(CGRect)frameRect bkgColor:(UIColor *)backgroundColor {
CFAttributedStringRef currentText = (__bridge CFAttributedStringRef)(textToDraw);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);
// Draw background when a color is set
if (backgroundColor) {
[backgroundColor set];
CGRect backgroundFrame = CGRectMake(frameRect.origin.x, frameRect.origin.y -backgroundOffset, frameRect.size.width, frameRect.size.height -3);
//CGRect backgroundFrame = CGRectMake(frameRect.origin.x, frameRect.origin.y -2, frameRect.size.width, frameRect.size.height -3);
CGContextFillRect( UIGraphicsGetCurrentContext(), backgroundFrame);
[[UIColor whiteColor] set];
}
CGMutablePathRef framePath = CGPathCreateMutable();
CGPathAddRect(framePath, NULL, frameRect);
// Get the frame that will do the rendering.
CFRange currentRange = CFRangeMake(0, 0);
CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
CGPathRelease(framePath);
// Get the graphics context.
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// Put the text matrix into a known state so no old scaling factors are left in place.
CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
int adjust = frameRect.origin.y * 2 + frameRect.size.height;
// Core Text draws from the bottom-left corner up, so flip
// the current transform prior to drawing.
CGContextTranslateCTM(currentContext, 0, adjust);
CGContextScaleCTM(currentContext, 1.0, -1.0);
// Draw the frame.
CTFrameDraw(frameRef, currentContext);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGContextTranslateCTM(currentContext, 0, (-1)*adjust);
CFRelease(frameRef);
CFRelease(framesetter);
backgroundColor = nil;
}