Skip to content

Instantly share code, notes, and snippets.

@jsooriah
Created April 18, 2012 13:51
Show Gist options
  • Save jsooriah/2413694 to your computer and use it in GitHub Desktop.
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.
#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment