GDI+编程10个基本技巧
补充:“橡皮筋”
创建绘图表面
创建绘图表面有两种常用的方法。下面设法得到PictureBox的绘图表面。
private void Form1_Load(object sender, System.EventArgs e)
{
//得到pictureBox1的绘图表面
Graphics g = this.pictureBox1.CreateGraphics();
}
private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
//得到pictureBox1的绘图表面
Graphics g = e.Graphics;
}
可以利用Graphics对象绘制出各种图形图案。控件的Paint事件和OnPaint方法都可以绘图都是好时机。在OnPaint方法里绘制图案一定从参数e里面得到Graphics属性。下面是两个例子。
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.Clear(Color.White);
float x, y, w, h;
x = this.Left+2;
y = this.Top+2;
w = this.Width-4;
h = this.Height-4;
Pen pen = new Pen(Color.Red, 2);
e.Graphics.DrawRectangle(pen, x, y, w, h);
base.OnPaint (e);
}
private void PictureBoxII_Resize(object sender, EventArgs e)
{
this.Invalidate();
}
private void button1_Click(object sender, System.EventArgs e)
{
this.pictureBoxII1.CreateGraphics().FillEllipse(
Brushes.Blue, 10, 20, 50, 100);
}
和文本有关的三个类:
FontFamily——定义有着相似的基本设计但在形式上有某些差异的一组字样。无法继承此类。
Font——定义特定的文本格式,包括字体、字号和字形属性。无法继承此类。
FontStyle——该枚举用来指定字形信息。包括:粗体、斜体、普通文本、下划线、中间穿过的横线。可以任意组合,像下面这样:
FontStyle fs = FontStyle.Underline | FontStyle.Italic | FontStyle.Strikeout | FontStyle.Bold;//任意组合
Font f = new Font("宋体", 20, fs);
e.Graphics.DrawString("aaaaa", f, Brushes.Black, 50, 50);
StringFormat——封装文本布局信息(如对齐方式和行距),显示操作(如省略号插入和国家标准 (National) 数字位替换)和 OpenType 功能。无法继承此类。
下面的程序显示了一段文字。
private void button2_Click(object sender, System.EventArgs e)
{
Graphics g = this.pictureBoxII1.CreateGraphics();
g.FillRectangle(Brushes.White, this.pictureBoxII1.ClientRectangle);
string s = "aaaaaaaaaaaaaaaaaaaaaaaaaa";
FontFamily fm = new FontFamily("ËÎÌå");
Font f = new Font(fm, 20, FontStyle.Bold, GraphicsUnit.Point);
RectangleF rectF = new RectangleF(30, 20, 180, 205);
StringFormat sf = new StringFormat();
SolidBrush sbrush = new SolidBrush(Color.FromArgb(255, 0, 0, 255));
sf.LineAlignment = StringAlignment.Center;
sf.FormatFlags = StringFormatFlags.DirectionVertical;
g.DrawString(s, f, sbrush, rectF, sf);
}
GDI+<