iOS – 如何find与给定的CGRect相同的高度正确的字体大小(以点为单位)?

标题几乎可以解释它。 我有一个图像,我正在绘制文本。 我希望文本的大小根据图像的大小,并希望find一种方法来获得一个字体的高度只是比图像本身短一点。

好吧,对于那些认为迭代不可避免的人来说,

NSString *string = @"The string to render"; CGRect rect = imageView.frame; UIFont *font = [UIFont fontWithSize:12.0]; // find the height of a 12.0pt font CGSize size = [string sizeWithFont:font]; float pointsPerPixel = 12.0 / size.height; // compute the ratio // Alternatively: // float pixelsPerPoint = size.height / 12.0; float desiredFontSize = rect.size.height * pointsPerPixel; // Alternatively: // float desiredFontSize = rect.size.height / pixelsPerPoint; 

desiredFontSize将包含其高度与指定矩形的高度完全相同的点的字体大小。 你可能要乘以0.8,使字体比矩形的实际尺寸稍微小一点,以使它看起来不错。

从这里

http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/CoreText_Programming/Operations/Operations.html

 CGFloat GetLineHeightForFont(CTFontRef iFont) { CGFloat lineHeight = 0.0; check(iFont != NULL); // Get the ascent from the font, already scaled for the font's size lineHeight += CTFontGetAscent(iFont); // Get the descent from the font, already scaled for the font's size lineHeight += CTFontGetDescent(iFont); // Get the leading from the font, already scaled for the font's size lineHeight += CTFontGetLeading(iFont); return lineHeight; } 

要使用这个,猜测一个点的大小,find它的行高(你可能会或可能不关心领先)。 然后使用答案和高度之间的比例来缩放点的大小。 我不认为你保证高度是完全正确的 – 如果你关心它的确切,你必须迭代,直到它足够接近(使用新的大小作为新的猜测)。

注意:这使得您的字体大小将始终小于CGRect的磅值。 根据需要调整方法以纠正该假设。

尝试这个。 适用于创build字体的三种主要方法中的任何一种。 应该是不言而喻的,但增量是您希望在检查之间减less的数量。 如果你不关心精确的尺寸,那就把这个数字做得更大,以便更快的速度。 如果你真的在意,请将其缩小以提高准确性。

 - (UIFont *)systemFontForRectHeight:(CGFloat)height increment:(CGFloat)increment { UIFont *retVal = nil; for (float i = height; i > 0; i = i - increment) { retVal = [UIFont systemFontOfSize:i]; if ([retVal lineHeight] < height) break; } return retVal; } - (UIFont *)boldSystemFontForRectHeight:(CGFloat)height increment:(CGFloat)increment { UIFont *retVal = nil; for (float i = height; i > 0; i = i - increment) { retVal = [UIFont boldSystemFontOfSize:i]; if ([retVal lineHeight] < height) break; } return retVal; } - (UIFont *)fontNamed:(NSString *)name forRectHeight:(CGFloat)height increment:(CGFloat)increment { UIFont *retVal = nil; for (float i = height; i > 0; i = i - increment) { retVal = [UIFont fontWithName:name size:i]; if ([retVal lineHeight] < height) break; } return retVal; }