mem*_*ons 8 iphone cocoa-touch objective-c ios
我试图找到适合给定字符串的给定矩形的最大字体大小.该算法的目标是尽可能用尽可能大的字体填充尽可能多的矩形.我的方法 - 从我在网上找到的方法修改 - 做得很好,但它通常不会填满整个矩形.我很想看到如何改进这个算法的一些合作,以便每个人都可以从中受益:
-(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;
}
对于给定的矩形和字符串,使用以下方法计算可以适合的字体。
您可以将字体更改为您需要的字体。此外,如果需要,您可以添加默认字体高度;
方法是不言自明的。
-(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;
 }
| 归档时间: | 
 | 
| 查看次数: | 3396 次 | 
| 最近记录: |