Created
April 18, 2012 13:51
-
-
Save jsooriah/2413694 to your computer and use it in GitHub Desktop.
Gives the height an NSAttributedString will take up when constrained to a given width.
This file contains 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
#import <CoreText/CoreText.h> | |
@interface NSAttributedString (Height) | |
-(CGFloat)boundingHeightForWidth:(CGFloat)inWidth; | |
@end |
This file contains 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
#import "NSAttributedString+height.h" | |
@implementation NSAttributedString (Height) | |
- (CGFloat)boundingHeightForWidth:(CGFloat)inWidth { | |
CGFloat height = 0; | |
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString ( (CFMutableAttributedStringRef) self); | |
CGRect box = CGRectMake(0,0, inWidth, CGFLOAT_MAX); | |
CFIndex startIndex = 0; | |
CGMutablePathRef path = CGPathCreateMutable(); | |
CGPathAddRect(path, NULL, box); | |
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(startIndex, 0), path, NULL); | |
CFArrayRef lineArray = CTFrameGetLines(frame); | |
CFIndex j = 0, lineCount = CFArrayGetCount(lineArray); | |
CGFloat lineHeight, ascent, descent, leading; | |
for (j=0; j < lineCount; j++) { | |
CTLineRef currentLine = (CTLineRef)CFArrayGetValueAtIndex(lineArray, j); | |
CTLineGetTypographicBounds(currentLine, &ascent, &descent, &leading); | |
lineHeight = ascent + descent + leading; | |
height += lineHeight; | |
} | |
CFRelease(frame); | |
CFRelease(path); | |
CFRelease(framesetter); | |
return height; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment