简体   繁体   中英

How to set font color and style for PDF using core text?

If I create a PDF using core text framework, it will not allow me to set color and font style. Is there any problem with "core text" framework?

I am using below code for setting color :

CGContextRef    currentContext = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(currentContext, 1.0, 0.0, 0.0, 1.0);  //This is not working.

Try below code, in this code i've changed my font style and size with CTFontRef

+(void)drawText:(NSString*)textToDraw inFrame:(CGRect)frameRect
{
    CFStringRef stringRef = ( CFStringRef)textToDraw;

    CGColorSpaceCreateWithName(stringRef);

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]
                                         initWithString:textToDraw];
    CTFontRef helveticaBold;
    helveticaBold = CTFontCreateWithName(CFSTR("Helvetica-Bold"), 24.0, NULL);
    [string addAttribute:(id)kCTFontAttributeName
                   value:(id)helveticaBold
                   range:NSMakeRange(0, [string length])];
    [string addAttribute:(id)kCTForegroundColorAttributeName
                   value:(id)[UIColor whiteColor].CGColor
                   range:NSMakeRange(0, [string length])];

    CTFramesetterRef framesetter =    CTFramesetterCreateWithAttributedString((CFAttributedStringRef)string);

    CGMutablePathRef framePath = CGPathCreateMutable();

    CGPathAddRect(framePath, NULL, frameRect);
    CFRange currentRange = CFRangeMake(0, 0);
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
    CGPathRelease(framePath);

    CGContextRef    currentContext = UIGraphicsGetCurrentContext();

    CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);

    CGContextTranslateCTM(currentContext, 0, frameRect.origin.y*2);

    CGContextScaleCTM(currentContext, 1.0, -1.0);

    CTFrameDraw(frameRef, currentContext);

    CGContextScaleCTM(currentContext, 1.0, -1.0);

    CGContextTranslateCTM(currentContext, 0, (-1)*frameRect.origin.y*2);

    CFRelease(frameRef);
    CFRelease(string);
    CFRelease(framesetter);
}

you can follow this Link also Example

Hope this helps you, Happy Coding

You can create color object like this:

UIColor *colour = [UIColor colorWithRed:0 green:1 blue:0 alpha:0];

And fill colour:

CGContextSetFillColorWithColor(ctx, colour.CGColor);

If you are not using ARC, you need to retain and release color appropriately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM