Skip to content

Instantly share code, notes, and snippets.

@acrist
Created August 4, 2011 16:35
Show Gist options
  • Save acrist/1125585 to your computer and use it in GitHub Desktop.
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.
#import <CoreText/CoreText.h>
@interface NSAttributedString (Height)
-(CGFloat)boundingHeightForWidth:(CGFloat)inWidth;
@end
#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
@kiranb
Copy link

kiranb commented May 2, 2014

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment