Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Font Size to Fit Frame - Core Text - NSAttributedString - iOS

Tags:

I have some text which I am drawing into a fixed frame via an NSAttributedString (code below). At the moment I am hard coding the text size to 16. My question is, is there a way to calculate the best fit size for the text for the given frame ?

- (void)drawText:(CGContextRef)contextP startX:(float)x startY:(float) y withText:(NSString *)standString {     CGContextTranslateCTM(contextP, 0, (bottom-top)*2);     CGContextScaleCTM(contextP, 1.0, -1.0);      CGRect frameText = CGRectMake(1, 0, (right-left)*2, (bottom-top)*2);      NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:standString];     [attrString addAttribute:NSFontAttributeName                       value:[UIFont fontWithName:@"Helvetica-Bold" size:16.0]                       range:NSMakeRange(0, attrString.length)];      CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)(attrString));     struct CGPath * p = CGPathCreateMutable();     CGPathAddRect(p, NULL, frameText);     CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0,0), p, NULL);      CTFrameDraw(frame, contextP); } 
like image 854
GuybrushThreepwood Avatar asked Dec 09 '13 10:12

GuybrushThreepwood


1 Answers

Here is a simple piece of code that will figure out the maximum font size to fit within the bounds of a frame:

UILabel *label = [[UILabel alloc] initWithFrame:frame]; label.text = @"Some text"; float largestFontSize = 12; while ([label.text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:largestFontSize]}].width > modifierFrame.size.width) {      largestFontSize--; } label.font = [UIFont systemFontOfSize:largestFontSize]; 
like image 186
user3072402 Avatar answered Nov 12 '22 22:11

user3072402