Resize text size of a label when the text gets longer than the label size?

后端 未结 7 674
旧巷少年郎
旧巷少年郎 2020-12-05 07:47

I have a label that shows the file name .. I had to set AutoSize of the label to False for designing.
So when the file name text got longer tha

7条回答
  •  执念已碎
    2020-12-05 08:03

    With inspiration from @bnguyen82 i came up with something that works all the way.

    public static void ScaleLabel(Label label, float stepSize = 0.5f)
    {
        //decrease font size if text is wider or higher than label
        while (lblTextSize() is Size s && s.Width > label.Width || s.Height > label.Height)
        {
            label.Font = new Font(label.Font.FontFamily, label.Font.Size - stepSize, label.Font.Style);
        }
    
        //increase font size if label width is bigger than text size
        while (label.Width > lblTextSize().Width)
        {
            var font = new Font(label.Font.FontFamily, label.Font.Size + stepSize, label.Font.Style);
            var nextSize = TextRenderer.MeasureText(label.Text, font);
    
            //dont make text width or hight bigger than label
            if (nextSize.Width > label.Width || nextSize.Height > label.Height)
                break;
    
            label.Font = font;
        }
    
        Size lblTextSize() => TextRenderer.MeasureText(label.Text,
            new Font(label.Font.FontFamily, label.Font.Size, label.Font.Style));
    }
    

    PS: In order for this to work the label needs to have AutoSize = false and either to be docked or anchored.

提交回复
热议问题