- (void) drawText: (NSString *) text inRect: (CGRect) rect { CTFontRef font = CTFontCreateWithName (CFSTR("Helvetica"), 15.0, NULL); NSDictionary *attributes = @{ (__bridge id)kCTFontAttributeName : (__bridge id) font }; CFAttributedStringRef attrString = CFAttributedStringCreate (kCFAllocatorDefault, (__bridge CFStringRef) text, (__bridge CFDictionaryRef) attributes); CTFramesetterRef fsetter = CTFramesetterCreateWithAttributedString (attrString); CGPathRef path = CGPathCreateWithRect (rect, NULL); CTFrameRef frame = CTFramesetterCreateFrame (fsetter, CFRangeMake (0, 0), path, NULL); CGContextRef context = ...; CGContextSetTextMatrix (context, CGAffineTransformIdentity); CTFrameDraw (frame, context); CFRelease (font); CFRelease (attrString); CFRelease (fsetter); CGPathRelease (path); } // drawTextInRect
CTFramesetterRef fsetter = CTFramesetterCreateWithAttributedString (attrString); CFRange fitRange; CGSize frameSize = CTFramesetterSuggestFrameSizeWithConstraints (fsetter, CFRangeMake (0, 0), NULL, // frame attributes CGSizeMake (rect.size.width, CGFLOAT_MAX), &fitRange);
fitRange
is the range of characters that fit in. Given a height of CGFLOAT_MAX, this should be the entire string. frameSize
is the width and height the text will be wrapped in. A { 0, 0}
range means to use the whole string.