创建图形对象
在窗体或控件的 Paint 事件中接收对图形对象的引用,作为 PaintEventArgs 的一部分. 在为控件创建绘制代码时,通常会使用此方法来获取对图形对象的引用. 同样,您也可以在处理 PrintDocument 的 PrintPage 事件时获取作为 PrintPageEventArgs 的属性的图形对象.
- 或 -
调用某控件或窗体的 CreateGraphics 方法以获取对 Graphics 对象的引用,该对象表示该控件或窗体的绘图图面. 如果想在已存在的窗体或控件上绘图,请使用此方法.
- 或 -
由从 Image 继承的任何对象创建 Graphics 对象. 此方法在您需要更改已存在的图像时十分有用.
下面的部分给出了有关这些过程的详细信息.
Paint 事件处理程序中的 PaintEventArgs
当对控件的 PaintEventHandler 编程或对 PrintDocument 的 PrintPage 编程时,需提供一个图形对象作为 PaintEventArgs 或 PrintPageEventArgs 的属性之一.
获取对 Paint 事件的 PaintEventArgs 中 Graphics 对象的引用
1. 声明 Graphics 对象.
2. 分配变量以引用作为 PaintEventArgs 的一部分传递的 Graphics 对象.
3. 插入代码来绘制窗体或控件.
下面的示例演示了如何从 Paint 事件中的 PaintEventArgs 引用 Graphics 对象:
private void Form1_Paint(object sender,
System.Windows.Forms.PaintEventArgs pe)
{
// Declares the Graphics object and sets it to the Graphics object
// supplied in the PaintEventArgs.
Graphics g = pe.Graphics;
// Insert code to paint the form here.
}
CreateGraphics 方法
也可以使用控件或窗体的 CreateGraphics 方法来获取对 Graphics 对象的引用,该对象表示该控件或窗体的绘图图面.
用 CreateGraphics 方法创建 Graphics 对象
调用要用于呈现图形的窗体或控件的 CreateGraphics 方法.
Graphics g;
// Sets g to a graphics object representing the drawing surface of the
// control or form g is a member of.
g = this.CreateGraphics();
从 Image 对象创建
另外,可以从 Image 类派生的任何对象创建图形对象.
从 Image 创建 Graphics 对象
调用 Graphics.FromImage 方法,提供要从其创建 Graphics 对象的 Image 变量的名称.
下面的示例演示如何使用 Bitmap 对象:
Bitmap myBitmap = new Bitmap(@"C:\Documents and
Settings\Joe\Pics\myPic.bmp");
Graphics g = Graphics.FromImage(myBitmap);
说明
|
只能从非索引 .bmp 文件(如 16 位、24 位和 32 位的 .bmp 文件)创建
对象。 索引 .bmp 文件的像素将索引保存到颜色表中,相比而言,非索引 .bmp 文件的每个像素保存一种颜色。
|
来源: http://www.bubuko.com/infodetail-2469131.html