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);
}

任何帮助或建议将不胜感激。,在此先感谢。

4

1 回答 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);

我的问题,你会明白的。

于 2013-05-10T10:40:28.220 回答