|
|
2.1. 如何创建 Graphics 对象?
图形对象根据其用途有几种创建方式:
通过 OnPaint,使用 PaintEventArgs 中提供的对象:
//C#
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawLine(...);
}
'VB
Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
e.Graphics.DrawLine(...)
End Sub 'OnPaint
通过代码中的其他区域,该函数是 Control 的一个方法,可以用来创建任何控件的图形对象:
//C#
using System.Drawing;
Graphics g = this.CreateGraphics();
'VB
Imports System.Drawing
Dim g As Graphics = Me.CreateGraphics()
直接在一个位图中绘制:
//C#
using System.Drawing;
Bitmap bm = new Bitmap(10,10);
Graphics g = Graphics.FromImage(bm);
'VB
Imports System.Drawing
Dim bm As New Bitmap(10, 10)
Dim g As Graphics = Graphics.FromImage(bm)
2.2. 可以怎样优化 GDI+ 呈现?
当使用 Graphics 绘画调用时,有几种基本的编码实践可以帮助提高绘画速度:
• 只创建一个 Graphics 对象(或者使用来自 OnPaint 中的 PaintEventArgs 的 Graphics 对象)。
• 在屏幕外的位图中完成所有绘画,然后拖曳该位图,使它一次全部显示出来。
• 只重画图像的更改部分。
• 尽可能使绘制的源和目的大小相同(不要拉伸等等)。
也许最重要的实践是保留需要重画的项目的痕迹以便使出现的绘画量尽可能少。例如,如果拖曳光标跨过图像,就不需要重画整个图像。相反,只需重画前一个光标位置覆盖的图像部分。
2.3. 如何在窗体中绘制图像?
此示例显示了如何将一个图形作为窗体的背景图像显示:
http://samples.gotdotnet.com/qui ... doc/bkgndimage.aspx
2.4. 如何绘制具有透明度的图像?
绘制有透明度的图像需要一个指定透明颜色的 ImageAttributes 对象。当前,.NET Compact Framework 支持单种颜色的原色调透明度。虽然 SetColorKey 函数允许一个颜色范围,但最小和最大的颜色必须相同,否则会产生运行时 ArgumentException:
//C#
using System.Drawing.Imaging;
ImageAttributes attr = new ImageAttributes();
'VB
Imports System.Drawing.Imaging
Dim attr As New ImageAttributes()
以下代码演示了如何根据图像的左上像素设置透明色调。
//C#
attr.SetColorKey(bmp.GetPixel(0,0), bmp.GetPixel(0,0));
'VB
attr.SetColorKey(bmp.GetPixel(0,0), bmp.GetPixel(0,0))
也可以按照如下所述方法显式设置颜色:
//C#
attr.SetColorKey(Color.FromArgb(255,0,255),Color.FromArgb(255,0,255));
attr.SetColorKey(Color.Fuchsia, Color.Fuchsia);
'VB
attr.SetColorKey(Color.FromArgb(255,0,255),Color.FromArgb(255,0,255))
attr.SetColorKey(Color.Fuchsia, Color.Fuchsia)
然后可以用重载的 Graphics.DrawImage 函数(它将 ImageAttributes 对象作为一个参数)来绘制图像:
//C#
Rectangle dstRect = new Rectangle(0, 0, bmp.Width, bmp.Height);
g.DrawImage(bmp, dstRect, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, attr);
'VB
Dim dstRect As New Rectangle(0, 0, bmp.Width, bmp.Height)
g.DrawImage(bmp, dstRect, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, attr) |
|