0

私のアプリでは、サーバーから長さが不明なテキストを取得します。ラベルの長さよりも大きい場合にテキストが切り取られないように、ラベルの高さを変更する方法についてアイデアを提供できますか。

4

2 に答える 2

1

を使用しGraphics.MeasureStringます。簡単な例を次に示します。

public class MyForm : Form
{
    private string m_text;

    public string NewLabelText 
    { 
        get { return m_text; }
        set 
        {
             m_text = value;
             this.Refresh();
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if (NewLabelText != null)
        {
            var size = e.Graphics.MeasureString(NewLabelText, label1.Font);
            label1.Width = (int)size.Width;
            label1.Height = (int)size.Height;
            label1.Text = NewLabelText;
            NewLabelText = null;
        }

        base.OnPaint(e);
    }
}
于 2012-12-22T19:17:20.067 に答える
0

質問に採用されたctackeのソリューションを使用する(ラベルの幅が一定):

protected override void OnPaint(PaintEventArgs e)
{
    if (NewLabelText != null)
    {
        //get the width and height of the text
        var size = e.Graphics.MeasureString(NewLabelText, label1.Font);
        if(size.Width>label1.Width){
            //how many lines are needed to display the text
            int iLines = (int)(System.Math.Round((size.Width / label1.Width)+.5));
            //multiply with using the normal height of a one line text
            //label1.Height=iLines*label1.PreferredHeight; //preferredHeight not supported by CF
            label1.Height=(int)(iLines*size.Height*1.1); // add some gutter
        }
        label1.Text = NewLabelText;
        NewLabelText = null;
    }

    base.OnPaint(e);
}

CFでそれをテストできませんでした。CF で PreferredHeight を使用できない可能性があります。その場合は、代わりに label1.height を使用してください。

于 2012-12-23T09:34:20.897 に答える