如何:手动呈现缓冲图形

如果要管理自己的缓冲图形,则需要能够创建和呈现图形缓冲区。 可以通过调用 Allocate 方法,创建与屏幕上绘图图面关联的 BufferedGraphics 类的实例。 此方法创建与特定呈现图面(如窗体或控件)关联的 BufferedGraphics 实例。 创建 BufferedGraphics 实例后,可以通过 Graphics 属性将图形绘制到它所表示的缓冲区。 执行所有图形操作后,可以通过调用 Render 方法将缓冲区的内容复制到屏幕。

注意

如果执行自己的渲染,则内存消耗将增加,但增加可能只是轻微的。

手动显示缓冲图形

  1. 获取对 BufferedGraphicsContext 类实例的引用。 有关详细信息,请参阅 如何:手动管理缓冲图形

  2. 通过调用 Allocate 方法创建 BufferedGraphics 类的实例,如以下代码示例所示。

    // This example assumes the existence of a form called Form1.
    BufferedGraphicsContext currentContext;
    BufferedGraphics myBuffer;
    // Gets a reference to the current BufferedGraphicsContext
    currentContext = BufferedGraphicsManager.Current;
    // Creates a BufferedGraphics instance associated with Form1, and with
    // dimensions the same size as the drawing surface of Form1.
    myBuffer = currentContext.Allocate(this.CreateGraphics(),
       this.DisplayRectangle);
    
    ' This example assumes the existence of a form called Form1.
    Dim currentContext As BufferedGraphicsContext
    Dim myBuffer As BufferedGraphics
    ' Gets a reference to the current BufferedGraphicsContext.
    currentContext = BufferedGraphicsManager.Current
    ' Creates a BufferedGraphics instance associated with Form1, and with 
    ' dimensions the same size as the drawing surface of Form1.
    myBuffer = currentContext.Allocate(Me.CreateGraphics, _
       Me.DisplayRectangle)
    
    
  3. 通过设置 Graphics 属性将图形绘制到图形缓冲区。 例如:

    // Draws an ellipse to the graphics buffer.
    myBuffer.Graphics.DrawEllipse(Pens.Blue, this.DisplayRectangle);
    
    ' Draws an ellipse to the graphics buffer.
    myBuffer.Graphics.DrawEllipse(Pens.Blue, Me.DisplayRectangle)
    
  4. 完成所有图形缓冲区的绘图操作后,调用 Render 方法以将缓冲区呈现到与其关联的绘图图面或指定的绘图图面,如以下代码示例所示。

    // This example assumes the existence of a BufferedGraphics instance
    // called myBuffer.
    // Renders the contents of the buffer to the drawing surface associated
    // with the buffer.
    myBuffer.Render();
    // Renders the contents of the buffer to the specified drawing surface.
    myBuffer.Render(this.CreateGraphics());
    
    ' Renders the contents of the buffer to the drawing surface associated 
    ' with the buffer.
    myBuffer.Render()
    ' Renders the contents of the buffer to the specified drawing surface.
    myBuffer.Render(Me.CreateGraphics)
    
  5. 完成图形呈现后,对 BufferedGraphics 实例调用 Dispose 方法以释放系统资源。

    myBuffer.Dispose();
    
    myBuffer.Dispose()
    

另请参阅