Created
August 4, 2011 16:35
-
-
Save acrist/1125585 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
If the attributes string is a rich text with different font size, Bold etc... this code is not giving back the proper height.
Do I have to make any changes in the code for such string?
Thanks!