如何在Winforms应用程序中使标签文本可缩放 [英] How can I make label text scale-able in Winforms application

查看:83
本文介绍了如何在Winforms应用程序中使标签文本可缩放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking for a way to make text in a label scale-able to it fit in entire parent container. The one way I can think of is to get the container size on window re-size and then increase or decrease font size accordingly, but that would limit its possibilities.

想知道是否有更好的方法,这可能更像Winforms应用程序中的anchor属性.

Wondering if there is a better way of doing this, that may work more like an anchor property in Winforms application.

推荐答案

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

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

这篇关于如何在Winforms应用程序中使标签文本可缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆