如何:绘制后台图像
更新:2007 年 11 月
通过使用不与窗体相关联的 Graphics 对象创建后台图像,可以减少绘制大图像时的闪烁。然后使用窗体的 Graphics 对象在屏幕上绘制图像。
示例
此示例重写 OnPaint 方法,以使用从一个大的后台位图派生的 Graphics 对象来创建该位图。然后使用从 PaintEventArgs 的 Graphics 属性返回的 Graphics 对象向屏幕上绘制该位图。
在窗体加载后,可能需要几分钟时间来显示图像。
Protected Overrides Sub OnPaint(e As PaintEventArgs)
Dim bmp As Bitmap
Dim gOff As Graphics
' Create a bitmap the size of the form.
bmp = New Bitmap(ClientRectangle.Width, ClientRectangle.Height)
Dim BlueBrush As New SolidBrush(Color.Blue)
Dim WhitePen As New Pen(Color.White, 3)
' Create a Graphics object that is not on the form.
gOff = Graphics.FromImage(bmp)
gOff.FillRectangle(new SolidBrush(color.red), 0, 0, _
bmp.Width, bmp.Height)
' Draw a complex bitmap of 1000 random rectangles. It will take a few
' seconds to draw.
Dim z As Integer
For z = 1 To 1000
' Generate a random number with
' seeds from the system clock.
Thread.Sleep(1)
Dim rx As New Random()
Thread.Sleep(1)
Dim ry As New Random()
' Create rectangles in the inner area of the form.
Dim rect As New Rectangle(rx.Next(10,200), ry.Next(10,200), 10, 10)
gOff.DrawRectangle(WhitePen, rect)
gOff.FillRectangle(BlueBrush, rect)
Next z
' Use the Graphics object from
' PaintEventArgs to draw the bitmap onto the screen.
e.Graphics.DrawImage(bmp, 0, 0, ClientRectangle, GraphicsUnit.Pixel)
gOff.Dispose()
End Sub
protected override void OnPaint(PaintEventArgs e)
{
Bitmap bmp;
Graphics gOff;
// Create a bitmap the size of the form.
bmp = new Bitmap(ClientRectangle.Width, ClientRectangle.Height);
SolidBrush BlueBrush = new SolidBrush(Color.Blue);
Pen WhitePen = new Pen(Color.White,3);
// Create a Graphics object that is not on the form.
gOff = Graphics.FromImage(bmp);
gOff.FillRectangle(new SolidBrush(Color.Red), 0, 0,
bmp.Width, bmp.Height);
// Draw a complex bitmap of 1000 random rectangles. It will take a few
// seconds to draw.
for (int z = 1; z <= 1000; z++)
{
// Generate a random number with
// seeds from the system clock.
Thread.Sleep(1);
Random rx = new Random();
Thread.Sleep(1);
Random ry = new Random();
// Create rectangles in the inner area of the form.
Rectangle rect = new Rectangle(rx.Next(10,200), ry.Next(10,200),
10, 10);
gOff.DrawRectangle(WhitePen, rect);
gOff.FillRectangle(BlueBrush, rect);
}
// Use the Graphics object from
// PaintEventArgs to draw the bitmap onto the screen.
e.Graphics.DrawImage(bmp, 0, 0, ClientRectangle, GraphicsUnit.Pixel);
gOff.Dispose();
}
编译代码
此示例需要引用下面的命名空间:
可靠编程
注意,应释放为进行后台绘制而创建的 Graphics 对象。由 PaintEventArgs 对象的 Graphics 属性返回的 Graphics 对象将由垃圾回收器销毁,不需要显式释放。