How to adjust font size of label to fit the rectangle?

前端 未结 14 717
独厮守ぢ
独厮守ぢ 2020-11-28 07:00

Yeah, there\'s this cool myLabel.adjustsFontSizeToFitWidth = YES; property. But as soon as the label has two lines or more, it won\'t resize the text to anythin

14条回答
  •  温柔的废话
    2020-11-28 07:11

    If someone is looking for a MonoTouch/Xamarin.iOS implementation, as I did ... here you go:

    private int BinarySearchForFontSizeForText(NSString text, int minFontSize, int maxFontSize, SizeF size)
    {
        if (maxFontSize < minFontSize) 
            return minFontSize;
    
        int fontSize = (minFontSize + maxFontSize) / 2;
        UIFont font = UIFont.BoldSystemFontOfSize(fontSize);
    
        var constraintSize = new SizeF(size.Width, float.MaxValue);
        SizeF labelSize = text.StringSize(font, constraintSize, UILineBreakMode.WordWrap);
    
        if (labelSize.Height >= size.Height + 10 && labelSize.Width >= size.Width + 10 && labelSize.Height <= size.Height && labelSize.Width <= size.Width)
            return fontSize;
        else if (labelSize.Height > size.Height || labelSize.Width > size.Width) 
            return BinarySearchForFontSizeForText(text, minFontSize, fontSize - 1, size);
        else 
            return BinarySearchForFontSizeForText(text, fontSize + 1, maxFontSize, size);
    }
    
    private void SizeLabelToRect(UILabel label, RectangleF labelRect)
    {
        label.Frame = labelRect;
    
        int maxFontSize = 300;
        int minFontSize = 5;
        int size = BinarySearchForFontSizeForText(new NSString(label.Text), minFontSize, maxFontSize, label.Frame.Size);
    
        label.Font = UIFont.SystemFontOfSize(size);
    }
    

    It's a translation of agarcian's code from Objective-C to C#, with a small modification: as the returning result has always been 0 (see the comment of borked) I am returning the calculated minFontSize, which results in a correct font size.

提交回复
热议问题