计算适合矩形的最大字体大小? [英] Calculate max font size that fits in a rect?
问题描述
我试图找到一个给定的字符串适合给定rect的最大字体大小。算法的目标是尽可能多地填充尽可能大的字体。我的方法 - 这是从我在网上找到的一个修改 - 是一个公平的工作,但它通常不填充整个rect。我希望看到一些关于如何改进这种算法的协作,以便每个人都可以从中受益:
I'm attempting to find the maximum font size that will fit in a given rect for a given string. The goal of the algorithm is to fill as much of the rect as possible with as large of a font as possible. My approach -- which is modified from one I found online -- does a fair job, but it often doesn't fill the entire rect. I'd love to see some collaboration on how to improve this algorithm so that everyone might benefit from it:
-(float) maxFontSizeThatFitsForString:(NSString*)_string
inRect:(CGRect)rect
withFont:(NSString *)fontName
onDevice:(int)device
{
// this is the maximum size font that will fit on the device
float _fontSize = maxFontSize;
float widthTweak;
// how much to change the font each iteration. smaller
// numbers will come closer to an exact match at the
// expense of increasing the number of iterations.
float fontDelta = 2.0;
// sometimes sizeWithFont will break up a word
// if the tweak is not applied. also note that
// this should probably take into account the
// font being used -- some fonts work better
// than others using sizeWithFont.
if(device == IPAD)
widthTweak = 0.2;
else
widthTweak = 0.2;
CGSize tallerSize =
CGSizeMake(rect.size.width-(rect.size.width*widthTweak), 100000);
CGSize stringSize =
[_string sizeWithFont:[UIFont fontWithName:fontName size:_fontSize]
constrainedToSize:tallerSize];
while (stringSize.height >= rect.size.height)
{
_fontSize -= fontDelta;
stringSize = [_string sizeWithFont:[UIFont fontWithName:fontName
size:_fontSize]
constrainedToSize:tallerSize];
}
return _fontSize;
}
推荐答案
使用以下方法计算
您可以将字体更改为所需的字体。
此外,如果需要,您可以添加默认字体高度;
You can change the font to the one which you require. Also, If required you can add a default font height;
方法是自解释的。
-(UIFont*) getFontTofitInRect:(CGRect) rect forText:(NSString*) text {
CGFloat baseFont=0;
UIFont *myFont=[UIFont systemFontOfSize:baseFont];
CGSize fSize=[text sizeWithFont:myFont];
CGFloat step=0.1f;
BOOL stop=NO;
CGFloat previousH;
while (!stop) {
myFont=[UIFont systemFontOfSize:baseFont+step ];
fSize=[text sizeWithFont:myFont constrainedToSize:rect.size lineBreakMode:UILineBreakModeWordWrap];
if(fSize.height+myFont.lineHeight>rect.size.height){
myFont=[UIFont systemFontOfSize:previousH];
fSize=CGSizeMake(fSize.width, previousH);
stop=YES;
}else {
previousH=baseFont+step;
}
step++;
}
return myFont;
}
这篇关于计算适合矩形的最大字体大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!