代碼如下:
public partial class Stringformat : Form
...{
public Stringformat()
...{
InitializeComponent();
SetStyle(ControlStyles.Opaque, true);
Point p = new Point(0, 0);
Size s = new Size(500, 300);
//Bounds = new Rectangle(0, 0, 500, 300);
Bounds = new Rectangle(p, s);//窗體大小及相對於父客體的位置(0,0)
}
protected override void OnPaint(PaintEventArgs e)//重定義基類OnPaint()方法
...{
Graphics g = e.Graphics;
int y = 0;
g.FillRectangle(Brushes.White, ClientRectangle);//繪制窗體背景色
Rectangle rect = new Rectangle(0, y, 400, Font.Height);
//g.FillRectangle(Brushes.Blue, rect);//墳兗一個矩形
g.DrawRectangle(Pens.Blue, rect);//繪製一個矩形
g.DrawString("This text is left justified.", Font, Brushes.Black, rect);
y += Font.Height + 20;
//Font.Dispose();//沒有創建對象,無須釋放資源
Font afont = new Font("Arial", 16, FontStyle.Bold | FontStyle.Italic);
rect = new Rectangle(0, y, 400, afont.Height);
g.DrawRectangle(Pens.Blue, rect);
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Far;
g.DrawString("This text is right justified.", afont, Brushes.Blue, rect,sf);
y += afont.Height + 20;
afont.Dispose();//創建了對象,須釋放資源
afont = new Font("Courier Ncw", 12, FontStyle.Underline|FontStyle.Bold);
rect = new Rectangle(0, y, 400, afont.Height);
g.DrawRectangle(Pens.Blue, rect);
sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
g.DrawString("This text is centered, and unederlined.", afont, Brushes.Blue, rect, sf);
y += afont.Height + 20;
afont.Dispose();
afont = new Font("Times New Roman", 12);
rect = new Rectangle(0, y, 400, afont.Height * 3);
g.DrawRectangle(Pens.Blue, rect);
string longString = "This text is much longer, and drawn ";
longString += "into a rectangle that is higher than ";
longString += "one line,so that it will wrap. It is ";
longString += "very easy to wrap text using GDI+.";
g.DrawString(longString, afont, Brushes.Black, rect);
afont.Dispose();
}
}運行效果圖:

本文通过一个实例展示了如何使用GDI+在窗体上绘制不同格式的文本,包括左对齐、右对齐、居中显示以及换行显示等效果,并详细介绍了绘制过程中的关键步骤。
1786

被折叠的 条评论
为什么被折叠?



