iOS动态生成PDF,使用所需的文本字体类型和字体颜色

4

我正在从我的应用程序创建动态PDF。在某些情况下,我希望我的文本以所需的颜色写入PDF。我该如何做到这一点?

我正在使用CoreText。

以下是我绘制PDF文本的代码:

+(void)drawText:(NSString*)textToDraw inFrame:(CGRect)frameRect
{
    frameRect.origin.y = frameRect.origin.y + frameRect.size.height; // New line
    CFStringRef stringRef = ( CFStringRef)textToDraw;
    CGColorSpaceCreateWithName(stringRef);
    CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, stringRef, NULL);
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);
    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. This ensures
    // that no old scaling factors are left in place.
    CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
    // Core Text draws from the bottom-left corner up, so flip
    // the current transform prior to drawing.
    CGContextTranslateCTM(currentContext, 0, frameRect.origin.y*2);
    CGContextScaleCTM(currentContext, 1.0, -1.0);
    // Draw the frame.
    CTFrameDraw(frameRef, currentContext);
    CGContextScaleCTM(currentContext, 1.0, -1.0);
    CGContextTranslateCTM(currentContext, 0, (-1)*frameRect.origin.y*2);
    CFRelease(frameRef);
    //CFRelease(stringRef);
    CFRelease(framesetter);
}

任何帮助或建议都将不胜感激,提前感谢。

1
请查看此链接:http://www.cocoanetics.com/2011/01/befriending-core-text/ - Deepesh
1个回答

0

如果您正在使用coretext,请尝试

CTFontRef font = CTFontCreateWithName((CFStringRef)@"Helvetica", 16.0f, nil);
CFAttributedStringSetAttribute(textString,CFRangeMake(0, strLength-1), kCTFontAttributeName, font);

你也可以尝试使用CGContextSetFont

NSString *fontName = @"Helvetica";
CGFontRef fontRef = CGFontCreateWithFontName((__bridge CFStringRef)fontName);
CGContextSetFont(context, fontRef);
CGContextSetFontSize(context, 30);

看看我的问题,你就会有一个想法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接