Skip to content

Instantly share code, notes, and snippets.

@mkdynamic
Forked from dkasper/CoreTextLabel.h
Created October 4, 2012 18:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkdynamic/3835369 to your computer and use it in GitHub Desktop.
Save mkdynamic/3835369 to your computer and use it in GitHub Desktop.
A multiline label drawn with core text. Needed it for line spacing, can easily be modified to use any core text properties though.
//
// CoreTextLabel.h
// Frost
//
// Created by David Kasper on 10/1/12.
//
#import <UIKit/UIKit.h>
#import <CoreText/CoreText.h>
@interface CoreTextLabel : UILabel
@property (assign) CGFloat lineSpacing;
@end
//
// CoreTextLabel.m
// Frost
//
// Created by David Kasper on 10/1/12.
//
#import "CoreTextLabel.h"
@implementation CoreTextLabel
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
// create a font, quasi systemFontWithSize:24.0
CTFontRef sysUIFont = CTFontCreateWithName((__bridge_retained CFStringRef)self.font.fontName, self.font.pointSize,NULL);
// create a naked string
NSString *string = self.text;
CGColorRef color = self.textColor.CGColor;
// now for the actual drawing
CGContextRef context = UIGraphicsGetCurrentContext();
// flip the coordinate system
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CTTextAlignment theAlignment = NSTextAlignmentToCTTextAlignment(self.textAlignment);
CFIndex theNumberOfSettings = 2;
CTParagraphStyleSetting theSettings[2] =
{
{ kCTParagraphStyleSpecifierAlignment, sizeof(CTTextAlignment),
&theAlignment},
{kCTParagraphStyleSpecifierLineSpacing, sizeof(CGFloat), &_lineSpacing}
};
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(theSettings, theNumberOfSettings);
NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:
(__bridge id)(sysUIFont), (NSString *)kCTFontAttributeName,
(__bridge id)color, (NSString *)kCTForegroundColorAttributeName,
paragraphStyle, (NSString *) kCTParagraphStyleAttributeName,
nil];
NSAttributedString *stringToDraw = [[NSAttributedString alloc] initWithString:string attributes:attributesDict];
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)stringToDraw);
//Create Frame
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, rect);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
//Draw Frame
CTFrameDraw(frame, context);
//Release all retained objects
CFRelease(path);
CFRelease(sysUIFont);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment