I want to draw a string in a single line on a UIView
that fits the width of the given rect(much like what adjustsFontSizeToFitWidth
for a UILabel
does when number of lines = 1). I'm trying to calculate the font size that will fit the rect as below.
- (UIFont *)fontforWidth:(CGFloat)width String:(NSString *)stringToFit {
CGFloat widthForIdealFontSize = [self widthForIdealFontSizeWithString:stringToFit];
CGFloat requiredFontSize = (KIdealFontSize/widthForIdealFontSize*width);
return [UIFont fontWithName:self.fontName size:(requiredFontSize)];
}
- (CGFloat)widthForIdealFontSizeWithString:(NSString *)inputString {
NSAttributedString *attrString = [[NSAttributedString alloc]initWithString:inputString attributes:@{NSFontAttributeName:[UIFont fontWithName:self.fontName size:KIdealFontSize]}];
CTLineRef line = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)attrString);
CGFloat ascent, descent, leading;
CGFloat width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
return width;
}
where #define KIdealFontSize 1000. I'm not able to get the exact value of the font size for some fonts like Zapfino where the string gets clipped when drawn. Is there a better way to calculate the exact font size that will fit the width for all fonts?