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); }
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With