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

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

    Based on the article provided by @brgerner, I'll provide the alternative implementation here, as that one marked as an answer is not so efficient nor complete as this one below:

    public class FontWizard
    {
        public static Font FlexFont(Graphics g, float minFontSize, float maxFontSize, Size layoutSize, string s, Font f, out SizeF extent)
        {
            if (maxFontSize == minFontSize)
                f = new Font(f.FontFamily, minFontSize, f.Style);
    
            extent = g.MeasureString(s, f);
    
            if (maxFontSize <= minFontSize)
                return f;
    
            float hRatio = layoutSize.Height / extent.Height;
            float wRatio = layoutSize.Width / extent.Width;
            float ratio = (hRatio < wRatio) ? hRatio : wRatio;
    
            float newSize = f.Size * ratio;
    
            if (newSize < minFontSize)
                newSize = minFontSize;
            else if (newSize > maxFontSize)
                newSize = maxFontSize;
    
            f = new Font(f.FontFamily, newSize, f.Style);
            extent = g.MeasureString(s, f);
    
            return f;
        }
    
        public static void OnPaint(object sender, PaintEventArgs e, string text)
        {
            var control = sender as Control;
            if (control == null)
                return;
    
            control.Text = string.Empty;    //delete old stuff
            var rectangle = control.ClientRectangle;
    
            using (Font f = new System.Drawing.Font("Microsoft Sans Serif", 20.25f, FontStyle.Bold))
            {
                SizeF size;
                using (Font f2 = FontWizard.FlexFont(e.Graphics, 5, 50, rectangle.Size, text, f, out size))
                {
                    PointF p = new PointF((rectangle.Width - size.Width) / 2, (rectangle.Height - size.Height) / 2);
                    e.Graphics.DrawString(text, f2, Brushes.Black, p);
                }
            }
        }
    }
    

    and the usage:

    val label = new Label();
    label.Paint += (sender, e) => FontWizard.OnPaint(sender, e, text);
    

提交回复
热议问题