CoreText.framework

From iPhone Development Wiki
Jump to: navigation, search
CoreText.framework
Public Framework
Availabile 3.0 – present
Class Prefix CT

CoreText.framework is a direct port of Mac OS X's Core Text framework. Core Text is a CoreFoundation-type framework for (styled) text layout. Prior to firmware 3.2, this framework was private.

Using CoreText to create styled label

This is an example view that can draw a CFAttributedString:

The view should be similar to this.
@interface StyledLabel : UIView {
	CFAttributedStringRef attribStr;
	CTFrameRef ctframe;
	CGMutablePathRef path;
}
@property(nonatomic) CFAttributedStringRef attributedString;
@end
 
 
@implementation StyledLabel
@dynamic attributedString;
-(CFAttributedStringRef)attributedString { return attribStr; }
-(void)_update {
	if (ctframe) {
		CFRelease(ctframe);
		ctframe = NULL;
	}
	CGPathRelease(path);
	path = NULL;
 
	if (attribStr) {
		CTFramesetterRef frs = CTFramesetterCreateWithAttributedString(attribStr);
		path = CGPathCreateMutable();
		CGPathAddRect(path, NULL, self.bounds);
		ctframe = CTFramesetterCreateFrame(frs, CFRangeMake(0, 0), path, NULL);
		CFRelease(frs);
	}
}
-(void)setFrame:(CGRect)frame {
	[super setFrame:frame];
	[self _update];
}
-(void)setBounds:(CGRect)bounds {
	[super setBounds:bounds];
	[self _update];
}
-(void)setAttributedString:(CFAttributedStringRef)as2 {
	if (attribStr != as2) {
		if (attribStr != NULL)
			CFRelease(attribStr);
		attribStr = as2 ? CFAttributedStringCreateCopy(NULL, as2) : NULL;
		[self _update];
	}
}
-(void)dealloc {
	if (attribStr)
		CFRelease(attribStr);
	CGPathRelease(path);
	if (ctframe)
		CFRelease(ctframe);
	[super dealloc];
}
-(void)drawRect:(CGRect)rect {
	CGContextRef c = UIGraphicsGetCurrentContext();
	CGContextSaveGState(c);
	CGContextTranslateCTM(c, 0, self.bounds.size.height);
	CGContextScaleCTM(c, 1, -1);
	CTFrameDraw(ctframe, c);
	CGContextRestoreGState(c);
}
@end

To use:

	StyledLabel* sl = [[StyledLabel alloc] initWithFrame:CGRectMake(60, 160, 100, 100)];
	sl.backgroundColor = [UIColor yellowColor];
	CFMutableAttributedStringRef as3 = CFAttributedStringCreateMutable(NULL, 0);
	CFAttributedStringBeginEditing(as3);
	CTFontRef font = CTFontCreateWithName(CFSTR("Georgia"), 32, NULL);
	CFAttributedStringReplaceString(as3, CFRangeMake(0, 0), CFSTR("Hello world!"));
	CFAttributedStringSetAttribute(as3, CFRangeMake(0, 12), kCTFontAttributeName, font);
	CFRelease(font);
	CFAttributedStringSetAttribute(as3, CFRangeMake(0, 5), kCTForegroundColorAttributeName, [UIColor redColor].CGColor);
	CFAttributedStringSetAttribute(as3, CFRangeMake(6, 6), kCTStrokeWidthAttributeName, [NSNumber numberWithFloat:2]);
	CFAttributedStringSetAttribute(as3, CFRangeMake(6, 6), kCTStrokeColorAttributeName, [UIColor blueColor].CGColor);
	CFAttributedStringEndEditing(as3);
 
	sl.attributedString = as3;
	CFRelease(as3);
 
	[window addSubview:sl];
	[sl release];

References