HOW TO:在螢幕外繪製影像

更新:2007 年 11 月

在繪製大型影像時,您可以使用與表單沒有關聯的 Graphics 物件,在螢幕外建立影像,以減少重繪閃動。然後使用表單的 Graphics 物件,在螢幕上繪製影像。

範例

這個範例會覆寫 OnPaint 方法,以使用從點陣圖衍生的 Graphics 物件,在螢幕外建立大型點陣圖。然後使用從 PaintEventArgsGraphics 屬性傳回的 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 物件,可由記憶體回收行程終結,而不需要明確地加以處置。

請參閱

其他資源

.NET Compact Framework 中的圖形與繪圖