且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Winforms应用程序中使标签文本可缩放

更新时间:2023-01-24 16:38:19

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

I knew the answer is hidden somewhere in graphic object and paint event, playing around with these 2 keywords solved my problem. Here is the solution that worked in my particular case.

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

I am simply changing the font size on paint event for my label as follows:

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函数如下所示:

Where as the NewFontSize function looks like this:

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

I also found this article helpful http://www.switchonthecode.com/tutorials/csharp-tutorial-font-scaling