在我的应用程序中,我将从长度未知的服务器获取文本。有人可以提出如何改变标签高度的想法,这样如果大于标签的长度,文本就不会被切断。
答案 0 :(得分: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);
}
}
答案 1 :(得分: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测试。可能是PreferredHeight在CF中不可用,如果是,请改用label1.height。