Created
December 29, 2013 17:48
-
-
Save darcyliu/8172847 to your computer and use it in GitHub Desktop.
Manual Line Breaking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CGContextRef context = UIGraphicsGetCurrentContext(); | |
// // Flip the coordinate system | |
// CGContextSetTextMatrix(context, CGAffineTransformIdentity); | |
// CGContextTranslateCTM(context, 0, self.bounds.size.height); | |
// CGContextScaleCTM(context, 1.0, -1.0); | |
UIFont *customFont = [UIFont systemFontOfSize:20]; | |
CTFontRef font = CTFontCreateWithName((CFStringRef)customFont.fontName, 20, NULL); | |
NSDictionary *attrs = @{(NSString *)kCTFontAttributeName: (__bridge id)font, | |
(NSString *)kCTForegroundColorAttributeName: (__bridge id)[UIColor blueColor].CGColor, | |
(NSString *)kCTUnderlineStyleAttributeName: @(NSUnderlineStyleSingle), | |
}; | |
// Make an attributed string | |
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Hello CoreText!" attributes:attrs]; | |
CFAttributedStringRef attributedStringRef = (CFAttributedStringRef)attributedString; | |
CTTypesetterRef typesetter = CTTypesetterCreateWithAttributedString(attributedStringRef); | |
CFIndex start = 0; | |
double width = CGRectGetWidth(self.bounds); | |
double height = CGRectGetHeight(self.bounds); | |
CFIndex stringLength = CFAttributedStringGetLength(attributedStringRef); | |
CGPoint textPosition = CGPointMake(0, height); | |
// this lineHeight may not equal customFont.lineHeight | |
// if you need line gap, you should control it by yourself | |
CGFloat lineHeight = CTFontGetAscent(font) + fabs(CTFontGetDescent(font)) + CTFontGetLeading(font); | |
while (start<stringLength) { | |
CFIndex count = CTTypesetterSuggestClusterBreak(typesetter, start, width); | |
CTLineRef line = CTTypesetterCreateLine(typesetter, CFRangeMake(start, count)); | |
// Get the offset needed to center the line. | |
float flush = 0.5; // 0,left; 0.5,center; 1,right | |
double penOffset = CTLineGetPenOffsetForFlush(line, flush, width); | |
// Move the given text drawing position by the calculated offset and draw the line. | |
CGContextSetTextPosition(context, textPosition.x + penOffset, textPosition.y - lineHeight); | |
CTLineDraw(line, context); | |
start += count; | |
textPosition.y -= lineHeight; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment