1

有没有人在从 NSAttributedString 绘制到带有日语文本的上下文后在 UIGraphicsEndPDFContext() 遇到 Xcode 失败?幸运的是,我第一次用日语测试我的代码时,我的 iPhone 脱机了,而且它工作正常。但是,很久以后,当我在模拟器中运行相同的代码时,它失败了,我花了很多时间尝试调试它。当尝试从 iPhone 或 iPad 上的 Xcode 硬连线到 Mac 时,它也会失败。似乎试图以这种方式从日语中的 Xcode 运行是问题所在。Mac设置为英语。

以下是我用于绘图的方法。它非常基于 Erica Sadun 在她的书“iOS 5 开发人员的食谱”中发布的示例,这对我来说是一本很好的早期读物。它被放置在 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;

}

4

0 回答 0