日期:2014-05-19  浏览次数:20839 次

要在一控件中显示字符串,很难,请求帮助。
winForm的。
是这样的,有一字符串,长度、行数都不一定(如:字符串中包含有换行符),要在一控件中显示,但显示的宽度不能超过400像素,如超过则换行。并且,还要调整控件的大小,使字符串在这一控件中正好显示完,周围没有剩余空间,也没不足。
最好有代码。
谢谢啦!!!!!!!!!

------解决方案--------------------
那你看一下这个代码,我没有更多的测试,楼主自己来检验结果吧,我简单的测试一下没有问题,代码如下,和上面的那个是不一样的,这个换行好使的:

private void button1_Click(object sender, EventArgs e)
{
string str = this.richTextBox1.Text;
using (Graphics g = this.panel1.CreateGraphics())
{
StringFormat format = new StringFormat( StringFormatFlags.DisplayFormatControl| StringFormatFlags.FitBlackBox| StringFormatFlags.LineLimit| StringFormatFlags.MeasureTrailingSpaces);
Size size = g.MeasureString(str, this.Font,400, format).ToSize();

if (size.Width > 400)
{
size = new Size(400, size.Width * size.Height / 400);
}
Rectangle rect = new Rectangle(0, 0, size.Width, size.Height);

this.panel1.Size = new Size(size.Width + 1, size.Height + 1);
g.Clear(this.panel1.BackColor);
g.DrawString(str, this.Font, SystemBrushes.WindowText, rect, format);
g.DrawRectangle(SystemPens.WindowText, rect);
}
}

------解决方案--------------------
string str = textBox1.Text;
Regex r = new Regex( "(\r\n) "); // Split on hyphens.
Size rowSize = new Size();
int row = 0;
string[] s = r.Split(str);
foreach (string lineString in s)
{
if (lineString!= "\r\n ")
{
rowSize = TextRenderer.MeasureText(lineString, this.Font);
if (rowSize.Width > 400)
{
row += rowSize.Width / 400 + 1;
}
else
{
row++;
}
}
}
textBox2.Size = new Size(400, (row+1) * rowSize.Height);
textBox2.Text = str;