Calculate max font size that fits in a rect?

后端 未结 3 1202
礼貌的吻别
礼貌的吻别 2021-01-02 14:31

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

3条回答
  •  旧时难觅i
    2021-01-02 15:02

    Use the following method to calculate the font which can fit, for a given rect and string.

    You can change the font to the one which you require. Also, If required you can add a default font height;

    Method is self explanatory.

    -(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;
    
     }
    

提交回复
热议问题