Calculate max font size that fits in a rect?

后端 未结 3 1181
礼貌的吻别
礼貌的吻别 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条回答
  • 2021-01-02 14:59

    There is no need to waste time doing loops. First, measure the text width and height at the max and min font point settings. Depending on whichever is more restrictive, width or height, use the following math:

    If width is more restrictive (i.e., maxPointWidth / rectWidth > maxPointHeight / rectHeight) use:

    pointSize = minPointSize + rectWidth * [(maxPointSize - minPointSize) / (maxPointWidth - minPointWidth)]
    

    Else, if height is more restrictive use:

    pointSize = minPointSize + rectHeight * [(maxPointSize - minPointSize) / (maxPointHeight - minPointHeight)]
    
    0 讨论(0)
  • 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;
    
     }
    
    0 讨论(0)
  • 2021-01-02 15:02

    It may be impossible to fill a rectangle completely.

    Say at a certain font size you have two lines of text, both filling the screen horizontally, but vertically you have almost but not quite three lines of space.

    If you increase the font size just a tiny bit, then the lines don't fit anymore, so you need three lines, but three lines don't fit vertically.

    So you have no choice but to live with the vertical gap.

    0 讨论(0)
提交回复
热议问题