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

后端 未结 7 680
旧巷少年郎
旧巷少年郎 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:05

    Label scaling

    private void scaleFont(Label lab)
    {
        Image fakeImage = new Bitmap(1, 1); //As we cannot use CreateGraphics() in a class library, so the fake image is used to load the Graphics.
        Graphics graphics = Graphics.FromImage(fakeImage);
    
        SizeF extent = graphics.MeasureString(lab.Text, lab.Font);
    
        float hRatio = lab.Height / extent.Height;
        float wRatio = lab.Width / extent.Width;
        float ratio = (hRatio < wRatio) ? hRatio : wRatio;
    
        float newSize = lab.Font.Size * ratio;
    
        lab.Font = new Font(lab.Font.FontFamily, newSize, lab.Font.Style);
    }
    

    TextRenderer Approach pointed out by @ToolmakerSteve in the comments

    private void ScaleFont(Label lab)
    {
        SizeF extent = TextRenderer.MeasureText(lab.Text, lab.Font);
    
        float hRatio = lab.Height / extent.Height;
        float wRatio = lab.Width / extent.Width;
        float ratio = (hRatio < wRatio) ? hRatio : wRatio;
    
        float newSize = lab.Font.Size * ratio;
    
        lab.Font = new Font(lab.Font.FontFamily, newSize, lab.Font.Style);
    }
    

提交回复
热议问题