//绘制函数
private static string DrawText(PaintEventArgs e, Font font)
{string s = "Tail Spin Toys 中\b文 + 数<d0.25.>{a2}(aBc)字,123.256 A,bc! Th.is is a test Measure string demo.30";
//string s = "This is a English string ......";
StringBuilder sb = new StringBuilder();
//Font font = new Font("仿宋", 13, FontStyle.Regular);
sb.AppendLine("字体:" + font.Name + ";字体大小:(" + font.SizeInPoints.ToString() + "----" + font.Size.ToString() + ")");
Point startPoint = new Point(10, 10);
// Set TextFormatFlags to no padding so strings are drawn together.
TextFormatFlags flags = TextFormatFlags.NoPadding;
Size proposedSize = new Size(0, 0); //new Size(int.MaxValue, int.MaxValue);
int width = 0;
int height = 0;
int spaceCount = 0;
//foreach (char c in s)
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
Size size = TextRenderer.MeasureText(e.Graphics, c.ToString(), font, proposedSize, flags);
Rectangle rect = new Rectangle(startPoint, size);
//两种绘制对比,表现上差异不是很大
TextRenderer.DrawText(e.Graphics, c.ToString(), font, startPoint, Color.Black, flags);
e.Graphics.DrawString(c.ToString(), font, Brushes.Blue, new PointF(startPoint.X, startPoint.Y), StringFormat.GenericTypographic);
startPoint.X += size.Width;
width += size.Width;
height = Math.Max(height, size.Height);
if (c == ' ')
{
sb.AppendLine("空格宽:" + size.Width.ToString() + ";位置:" + i.ToString());
spaceCount++;
}
sb.AppendLine("字符:" + c.ToString() + " 宽度:" + size.Width.ToString() + " 高度:" + size.Height.ToString());
}
sb.AppendLine("空格数:" + spaceCount);
Rectangle rect1 = new Rectangle(new Point(10, 10), new Size(width, height));
e.Graphics.DrawRectangle(Pens.Red, rect1);
return sb.ToString();
}