【问题标题】:How can I make label text scale-able in Winforms application如何在 Winforms 应用程序中使标签文本可缩放
【发布时间】:2012-11-30 08:15:56
【问题描述】:

我正在寻找一种方法来使标签中的文本可缩放以适合整个父容器。我能想到的一种方法是在窗口重新调整大小时获取容器大小,然后相应地增加或减小字体大小,但这会限制它的可能性。

想知道是否有更好的方法来做到这一点,它可能更像是 Winforms 应用程序中的锚属性。

【问题讨论】:

    标签: winforms c#-4.0 telerik label system.drawing


    【解决方案1】:

    这扩展了已接受的答案并为我工作:

    首先,我通过在 Designer 中设置一个普通标签来确定我的“黄金比例”,该标签的字体大小看起来不错,Label.Height 属性设置为 100。这就是我得到 48.0F 的字体 emSize 的地方。

    然后在 OnPaint 覆盖中,如果 100.0/48.0 的比例发生变化 则只需调整一次字体并保存新的比例(这样我们就不必制作新字体每次控件绘制时)。

    当您完成常规标签后,将其放入您的工具箱非常有用。

    public partial class LabelWithFontScaling : Label
    {
        public LabelWithFontScaling()
        {
            InitializeComponent();
        }
        private void InitializeComponent()
        {
            this.SuspendLayout();
            this.Name = "label1";
            this.Size = new System.Drawing.Size(250, 100);
            this.ResumeLayout(false);
        }
        float mRatio = 1.0F;
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            float ratio = e.ClipRectangle.Height / 100.0F;
            if ((ratio > 0.1) && (ratio != mRatio))
            {
                mRatio = ratio;
                base.Font = new Font(Font.FontFamily, 48.0F * ratio, Font.Style);
            }
        }
    

    【讨论】:

      【解决方案2】:

      我知道答案隐藏在图形对象和绘画事件的某个地方,使用这两个关键字解决了我的问题。这是在我的特定情况下有效的解决方案。

      我只是在为我的标签更改绘制事件的字体大小,如下所示:

      private void myLabel_Paint(object sender, PaintEventArgs e)
      {
           float fontSize = NewFontSize(e.Graphics, parentContainer.Bounds.Size, myLabel.Font, myLabel.Text);
           Font f = new Font("Arial", fontSize, FontStyle.Bold);
           myLabel.Font = f;
      }
      

      NewFontSize 函数如下所示:

      public static float NewFontSize(Graphics graphics, Size size, Font font, string str)
      {
          SizeF stringSize = graphics.MeasureString(str, font);
          float wRatio = size.Width / stringSize.Width;
          float hRatio = size.Height / stringSize.Height;
          float ratio = Math.Min(hRatio, wRatio);
          return font.Size * ratio;
      }
      

      我还发现这篇文章很有帮助 http://www.switchonthecode.com/tutorials/csharp-tutorial-font-scaling

      【讨论】:

      • 效果很好!谢谢。
      • @Xarialon 我 99% 确定 parentContainer 是 System.Windows.Forms 控件
      猜你喜欢
      • 2011-02-03
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-23
      相关资源
      最近更新 更多