Question

The IOS CGContext documentation says that various string output functions are now deprecated in favor of core text. The documentation just says "Use Core Text instead."

if I have

NSString *string ;

What would be the simple, currently approved method for drawing that text to the CGContext?

Was it helpful?

Solution

Here is my overridden drawRect: method to render attributed string with all explanation comments inside. By the time this method is called, UIKit has configured the drawing environment appropriately for your view and you can simply call whatever drawing methods and functions you need to render your content.

/*!
 * @abstract draw the actual coretext on the context
 *
 */
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    [self.backgroundColor setFill];
    CGContextFillRect(context, rect);

    if (_ctframe != NULL) CFRelease(_ctframe);

    if (_framesetter != NULL) CFRelease(_framesetter);

    //Creates an immutable framesetter object from an attributed string.
    //Use here the attributed string with which to construct the framesetter object.
    _framesetter = CTFramesetterCreateWithAttributedString((__bridge  
    CFAttributedStringRef)self.attributedString);


    //Creates a mutable graphics path.
    CGMutablePathRef mainPath = CGPathCreateMutable();

    if (!_path) {
       CGPathAddRect(mainPath, NULL, CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height));
    } else {
       CGPathAddPath(mainPath, NULL, _path);
    }

    //This call creates a frame full of glyphs in the shape of the path
    //provided by the path parameter. The framesetter continues to fill 
    //the frame until it either runs out of text or it finds that text
    //no longer fits.
    CTFrameRef drawFrame = CTFramesetterCreateFrame(_framesetter, CFRangeMake(0, 0),
    mainPath, NULL);

    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    // draw text
    CTFrameDraw(drawFrame, context);

        //clean up
        if (drawFrame) CFRelease(drawFrame);
    CGPathRelease(mainPath);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top