用Graphics.DrawString写文字,我想要的效果是,在一个宽度里显示文字,但文字的字数不定,可以实现自动换行及获取到这些文字的高度吗?
我用RectangleF试了,只是是固定的高度,如果文字太多,会显示不全。
调用DrawString函数时,传入一个边框矩形参数,文字会在此范围内自动换行。
因为字数不定,所以此矩形的高度也应该动态变化。
代码如下:
private void panel1_Paint(object sender, PaintEventArgs e)
{
string txtDescription = "这是一段非常长的字符串";
RectangleF descRect = new RectangleF();
using (Font useFont = new Font("SimSun", 28, FontStyle.Bold))
{
descRect.Location = new Point(30, 105);
descRect.Size = new Size(600, ((int)e.Graphics.MeasureString(txtDescription, useFont, 600, StringFormat.GenericTypographic).Height));
e.Graphics.DrawString(txtDescription, useFont, Brushes.Black, descRect);
}
}
MeasureString函数的用法可参考:
https://msdn.microsoft.com/en-us/library/system.drawing.graphics.measurestring(v=vs.110).aspx
用心回答每个问题,如果对您有帮助,请采纳答案好吗,谢谢!