我正在创建一个自定义控件,其中一部分是使用Graphics
类来向表单绘制文本.目前我正在使用以下代码来显示它:
private float _lineHeight { get { return this.Font.Size + 5; } } private void Control_Paint(object sender, PaintEventArgs e) { Graphics g = this.CreateGraphics(); Brush b = new SolidBrush(Colors[7]); g.DrawString("Hello World!", this.Font, b, 0, 2); g.DrawString("This has been a test of the emergency drawing system!", this.Font, b, 0, 2 + _lineHeight); }
我目前正在使用固定宽度字体,我想知道字体显示的宽度,但似乎没有这种信息的任何属性.有没有办法获得它?我想要它所以我可以在显示时正确包裹线条.
是的,你可以使用MeasureString从图形类
此方法返回SizeF结构,该结构表示由PageUnit属性指定的单位的大小,该大小由text参数指定的字符串(使用font参数绘制).
private void MeasureStringMin(PaintEventArgs e) { // Set up string. string measureString = "Measure String"; Font stringFont = new Font("Arial", 16); // Measure string. SizeF stringSize = new SizeF(); stringSize = e.Graphics.MeasureString(measureString, stringFont); // Draw rectangle representing size of string. e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height); // Draw string to screen. e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0)); }