如何确定打印时宽字符串? [英] How to determine width of a string when printed?

查看:241
本文介绍了如何确定打印时宽字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个自定义的控制,其中一部分是使用图形类绘制文本的形式。目前我使用下面的code,以显示它:

 私人浮动_lineHeight {{返回this.Font.Size + 5; }}
私人无效Control_Paint(对象发件人,PaintEventArgs的E)
{
    图形G = this.CreateGraphics();
    刷B =新SolidBrush(颜色[7]);

    g.DrawString(的Hello World!,this.Font,B,0,2);
    g.DrawString(这是紧急绘图系统的一个考验!
        this.Font,B,0,2 + _lineHeight);
}
 

我目前使用我固定宽度的字体,我想知道多宽字体显示,但没有出现任何属性这类信息。有没有获得它的一些方法?我希望它这样我就可以显示在正确换行。

解决方案

是的,你可以使用<一个href="http://msdn.microsoft.com/en-us/library/system.drawing.graphics.measurestring.aspx">MeasureString从图形

  

该方法返回的SizeF结构重新presents   的大小,在由指定的单位   在PageUnit属性字符串,   由文本参数作为指定   绘制的字体参数

 私人无效MeasureStringMin(PaintEventArgs的E)
{

    //设置字符串。
    字符串measureString =测量字符串;
    字体stringFont =新的字体(宋体,16);

    //测量字符串。
    的SizeF stringsize的=新的SizeF();
    stringsize的= e.Graphics.MeasureString(measureString,stringFont);

    //绘制矩形,再presenting串的大小。
    e.Graphics.DrawRectangle(新钢笔(Color.Red,1),0.0F,0.0F,stringSize.Width,stringSize.Height);

    //绘制字符串到屏幕。
    e.Graphics.DrawString(measureString,stringFont,Brushes.Black,新的PointF(0,0));
}
 

I'm creating a custom control, part of which is using the Graphics class to draw text to the form. Currently I'm using the following code to display it:

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);
}

I'm currently using fixedwidth fonts, and I'd like to know how wide the font will display, but there doesn't appear to be any properties for this sort of information. Is there some way of obtaining it? I want it so I can wrap lines properly when displayed.

解决方案

Yes, you can use MeasureString from the Graphics class

This method returns a SizeF structure that represents the size, in the units specified by the PageUnit property, of the string specified by the text parameter as drawn with the font parameter.

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));
}

这篇关于如何确定打印时宽字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆