Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使标签文本在Winforms应用程序中可缩放_Winforms_C# 4.0_Telerik_Label_System.drawing - Fatal编程技术网

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

如何使标签文本在Winforms应用程序中可缩放,winforms,c#-4.0,telerik,label,system.drawing,Winforms,C# 4.0,Telerik,Label,System.drawing,我正在寻找一种方法,使文本在标签规模能够适应整个父容器。我能想到的一种方法是在窗口重新调整大小时获得容器大小,然后相应地增加或减少字体大小,但这将限制其可能性 想知道是否有更好的方法来实现这一点,这可能更像Winforms应用程序中的锚属性。我知道答案隐藏在graphic object and paint event中的某个地方,使用这两个关键字解决了我的问题。这是在我的特殊情况下有效的解决方案 我只是按照如下方式更改了标签的“绘制事件”字体大小: private void myLabel_Pa

我正在寻找一种方法,使文本在标签规模能够适应整个父容器。我能想到的一种方法是在窗口重新调整大小时获得容器大小,然后相应地增加或减少字体大小,但这将限制其可能性


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

我知道答案隐藏在graphic object and paint event中的某个地方,使用这两个关键字解决了我的问题。这是在我的特殊情况下有效的解决方案

我只是按照如下方式更改了标签的“绘制事件”字体大小:

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;
}
我还发现这篇文章很有帮助

这是对公认答案的一点扩展,对我很有用:

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

然后在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);
        }
    }

效果很好!谢谢。@Xarialon我99%确定parentContainer是System.Windows.Forms控件