日期:2014-05-17  浏览次数:21262 次

C#矩形中插入字符,能够换行并且居中显示
C# code
 Rectangle rec = new Rectangle(50, 60, 50, 60);

           g.DrawString(node.NodeText, node.NodeTextFont, new SolidBrush(node.NodeTextColor), rec );
           g.DrawRectangle(Pens.Black, Rectangle.Round(rec)); 



现在已经能够实现换行了但是却不能居中显示,求助啊……


------解决方案--------------------
StringFormat sf = new StringFormat();
sf.AlignXXX = XXX.Center;
sf.LineAlignXXX = XXX.Center;
g.DrawString("text",this.Font,Brushes.Black,this.ClientRectangle,sf);

大概记得 貌似 就是这样的、、
------解决方案--------------------
Size size = TextRenderer.MeasureText(str, this.Font);
Rectangle rect = new Rectangle(20, 20, size.Height, (this.Font.Height)*str.Length);
e.Graphics.DrawString(str, this.Font, SystemBrushes.ControlText, rect);
e.Graphics.DrawRectangle(SystemPens.ControlText, rect);
------解决方案--------------------
string text2 = "Draw text in a rectangle by passing a RectF to the DrawString method.";
Font font2 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point);
try {
Rectangle rect2 = new Rectangle(30, 10, 100, 122);

// Specify the text is wrapped.
TextFormatFlags flags = TextFormatFlags.WordBreak;
TextRenderer.DrawText(e.Graphics, text2, font2, rect2, Color.Blue, flags);
e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rect2));
} finally {
font2.Dispose();
}


Graphics.DrawString 方法 (String, Font, Brush, PointF, StringFormat)

建立一个StringFormat对象,设置其Alignment和LineAlignment属性值均为center,再将该对象作为参数传递到方法中。
------解决方案--------------------
StringFormat centerStringFormat = new StringFormat();
centerStringFormat.Alignment = StringAlignment.Center;
centerStringFormat.LineAlignment = StringAlignment.Center;
g.DrawString("text",this.Font,Brushes.Black,this.ClientRectangle,centerStringFormat);