Exportar (0) Imprimir
Expandir Tudo
Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
Tradução
Original

BufferedGraphics Classe

Fornece um buffer de elementos gráficos para bufferização dupla.

Namespace:  System.Drawing
Assembly:  System.Drawing (em System.Drawing. dll)

public sealed class BufferedGraphics : IDisposable

The BufferedGraphics class allows you to implement custom double buffering for your graphics.Ele fornece um invólucro para um buffer de elementos gráficos, juntamente com métodos que você pode usar para gravar o buffer e processar seu conteúdo para um dispositivo de saída.

Os elementos gráficos que usam Duplo buferização pode reduzir ou eliminar a cintilação que é causada por redesenho um superfície de exibição.Quando você usar buffer duplo, gráficos atualizados primeiro são desenhados para um buffer na memória, e o conteúdo desse buffer é, em seguida, rapidamente gravado alguns ou todos a superfície exibida.This relatively BRIEF Substituir of the Graphics displayed geralmente reduces or eliminates the flicker that sometimes Occurs When Graphics are Updated.

ObservaçãoObservação:

The simplest way to use double buffering is to set the OptimizedDoubleBuffer control style flag on a control using the SetStyle method.Setting the OptimizedDoubleBuffer flag for a control redirects all painting for the control through a default graphics buffer, without requiring any additional code.This flag is set to true by default.

The BufferedGraphics class has no public constructor and must be created by the BufferedGraphicsContext for an application domain using its Allocate method.You can retrieve the BufferedGraphicsContext for the current application domain from the static BufferedGraphicsManager.Current property.

The Graphics property can be used for drawing to the graphics buffer.This property provides access to the Graphics object that draws to the graphics buffer allocated for this BufferedGraphics object.

The Render method with no arguments draws the contents of the graphics buffer to the surface specified when the buffer was allocated.Other overloads of the Render method allow you to specify a Graphics object or an IntPtr object that points to a device context to which to draw the contents of the graphics buffer.

For more information about drawing double-buffered graphics, see Duplo elementos gráficos Buffered.

The following code example demonstrates using a BufferedGraphics object to draw graphics using several types of buffering implementations.Como alternativa clicando a Formulárioulário inicia e pára um timer que faz com que Desenhar as atualizações.As atualizações desenhar permitem que você observe o efeito de buffer duplo.Clique com o botão direito do mouse os ciclos de formulário através os modos de desenho a seguir:

Cada modo, o texto é desenhado que identifica o modo atual e descreve o comportamento que ocorre quando cada botão do mouse é pressionado.

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace BufferingExample 
{
    public class BufferingExample : Form
    {
        private BufferedGraphicsContext context;
        private BufferedGraphics grafx;

	private byte bufferingMode;
	private string[] bufferingModeStrings = 
		{ "Draw to Form without OptimizedDoubleBufferring control style",
		  "Draw to Form using OptimizedDoubleBuffering control style",
		  "Draw to HDC for form" };

	private System.Windows.Forms.Timer timer1;
	private byte count;

        public BufferingExample() : base()
        {
            // Configure the Form for this example.
            this.Text = "User double buffering";
            this.MouseDown += new MouseEventHandler(this.MouseDownHandler);
            this.Resize += new EventHandler(this.OnResize);
            this.SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true );

            // Configure a timer to draw graphics updates.
	    timer1 = new System.Windows.Forms.Timer();
	    timer1.Interval = 200;
	    timer1.Tick += new EventHandler(this.OnTimer);

	    bufferingMode = 2;
	    count = 0;

            // Retrieves the BufferedGraphicsContext for the 
            // current application domain.
            context = BufferedGraphicsManager.Current;

            // Sets the maximum size for the primary graphics buffer
            // of the buffered graphics context for the application
            // domain.  Any allocation requests for a buffer larger 
            // than this will create a temporary buffered graphics 
            // context to host the graphics buffer.
            context.MaximumBuffer = new Size(this.Width+1, this.Height+1);

            // Allocates a graphics buffer the size of this form
            // using the pixel format of the Graphics created by 
            // the Form.CreateGraphics() method, which returns a 
            // Graphics object that matches the pixel format of the form.
            grafx = context.Allocate(this.CreateGraphics(), 
                 new Rectangle( 0, 0, this.Width, this.Height ));

	    // Draw the first frame to the buffer.
	    DrawToBuffer(grafx.Graphics);
        }

	private void MouseDownHandler(object sender, MouseEventArgs e)
        {
	    if( e.Button == MouseButtons.Right )
	    {
                 // Cycle the buffering mode.
	         if( ++bufferingMode > 2 )
                     bufferingMode = 0;

                 // If the previous buffering mode used 
                 // the OptimizedDoubleBuffering ControlStyle,
                 // disable the control style.
                 if( bufferingMode == 1 )
                     this.SetStyle( ControlStyles.OptimizedDoubleBuffer, true );

                 // If the current buffering mode uses
                 // the OptimizedDoubleBuffering ControlStyle,
                 // enabke the control style.
                 if( bufferingMode == 2 )
                     this.SetStyle( ControlStyles.OptimizedDoubleBuffer, false );

                 // Cause the background to be cleared and redraw.
                 count = 6;
    	         DrawToBuffer(grafx.Graphics);                 
		 this.Refresh();
	    }
	    else
	    {
                // Toggle whether the redraw timer is active.
		if( timer1.Enabled )
			timer1.Stop();
		else
			timer1.Start(); 
	    }
        }

	private void OnTimer(object sender, EventArgs e)
	{
            // Draw randomly positioned ellipses to the buffer.
	    DrawToBuffer(grafx.Graphics);

            // If in bufferingMode 2, draw to the form's HDC.
	    if( bufferingMode == 2 )            
                    // Render the graphics buffer to the form's HDC.
		    grafx.Render(Graphics.FromHwnd(this.Handle));            
            // If in bufferingMode 0 or 1, draw in the paint method.
	    else
  		    this.Refresh();
	}

        private void OnResize(object sender, EventArgs e)
        {
           // Re-create the graphics buffer for a new window size.
           context.MaximumBuffer = new Size(this.Width+1, this.Height+1);
           if( grafx != null )
           {
	       grafx.Dispose();
               grafx = null;               
           }
           grafx = context.Allocate(this.CreateGraphics(), 
               new Rectangle( 0, 0, this.Width, this.Height ));

           // Cause the background to be cleared and redraw.
           count = 6;
    	   DrawToBuffer(grafx.Graphics);                 
	   this.Refresh();
        }	

	private void DrawToBuffer(Graphics g)
	{
            // Clear the graphics buffer every five updates.
	    if( ++count > 5 )
            {
                count = 0;                
                grafx.Graphics.FillRectangle(Brushes.Black, 0, 0, this.Width, this.Height);
            }

            // Draw randomly positioned and colored ellipses.
	    Random rnd = new Random();
	    for( int i=0; i<20; i++ )
	    {
		int px = rnd.Next(20,this.Width-40);
		int py = rnd.Next(20,this.Height-40);
		g.DrawEllipse(new Pen(Color.FromArgb(rnd.Next(0, 255), rnd.Next(0,255), rnd.Next(0,255)), 1), 
			px, py, px+rnd.Next(0, this.Width-px-20), py+rnd.Next(0, this.Height-py-20)); 	    			
	    }

            // Draw information strings.
	    g.DrawString("Buffering Mode: "+bufferingModeStrings[bufferingMode], new Font("Arial", 8), Brushes.White, 10, 10);
            g.DrawString("Right-click to cycle buffering mode", new Font("Arial", 8), Brushes.White, 10, 22);
            g.DrawString("Left-click to toggle timed display refresh", new Font("Arial", 8), Brushes.White, 10, 34);
	}

	protected override void OnPaint(PaintEventArgs e)
        {            
	    grafx.Render(e.Graphics);
	}

        [STAThread]
        public static void Main(string[] args)
        {
	    Application.Run(new BufferingExample());
        }
    }
}



package BufferingExample; 

import System.*;
import System.ComponentModel.*;
import System.Drawing.*;
import System.Windows.Forms.*;

public class BufferingExample extends Form
{
    private BufferedGraphicsContext context;
    private BufferedGraphics grafx;
    private ubyte bufferingMode;
    private String bufferingModeStrings[] =  
        { "Draw to Form without OptimizedDoubleBufferring control style", 
        "Draw to Form using OptimizedDoubleBuffering control style", 
        "Draw to HDC for form" };
    private System.Windows.Forms.Timer timer1;
    private ubyte count;

    public BufferingExample()
    {
        super();
        // Configure the Form for this example.
        this.set_Text("User double buffering");
        this.add_MouseDown(new MouseEventHandler(this.MouseDownHandler));
        this.add_Resize(new EventHandler(this.OnResize));
        this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
        // Configure a timer to draw graphics updates.
        timer1 = new System.Windows.Forms.Timer();
        timer1.set_Interval(200);
        timer1.add_Tick(new EventHandler(this.OnTimer));
        bufferingMode = 2;
        count = 0;
        // Retrieves the BufferedGraphicsContext for the 
        // current application domain.
        context = BufferedGraphicsManager.get_Current();
        // Sets the maximum size for the primary graphics buffer
        // of the buffered graphics context for the application
        // domain.  Any allocation requests for a buffer larger 
        // than this will create a temporary buffered graphics 
        // context to host the graphics buffer.
        context.set_MaximumBuffer(new Size(this.get_Width() + 1, this.get_Height() + 1));
        // Allocates a graphics buffer the size of this form
        // using the pixel format of the Graphics created by 
        // the Form.CreateGraphics() method, which returns a 
        // Graphics object that matches the pixel format of the form.
        grafx = context.Allocate(this.CreateGraphics(), new Rectangle(0, 0, this.get_Width(), this.get_Height()));
        // Draw the first frame to the buffer.
        DrawToBuffer(grafx.get_Graphics());
    } //BufferingExample

    private void MouseDownHandler(Object sender, MouseEventArgs e)
    {
        if (e.get_Button().Equals(MouseButtons.Right)) {
            // Cycle the buffering mode.
            if (++bufferingMode > 2) {
                bufferingMode = 0;
            }

            // If the previous buffering mode used 
            // the OptimizedDoubleBuffering ControlStyle,
            // disable the control style.
            if (bufferingMode == 1) {
                this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            }

            // If the current buffering mode uses
            // the OptimizedDoubleBuffering ControlStyle,
            // enabke the control style.
            if (bufferingMode == 2) {
                this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
            }

            // Cause the background to be cleared and redraw.
            count = 6;
            DrawToBuffer(grafx.get_Graphics());
            this.Refresh();
        }
        else {
            // Toggle whether the redraw timer is active.
            if (timer1.get_Enabled()) {
                timer1.Stop();
            }
            else {
                timer1.Start();
            }
        }
    } //MouseDownHandler

    private void OnTimer(Object sender, EventArgs e)
    {
        // Draw randomly positioned ellipses to the buffer.
        DrawToBuffer(grafx.get_Graphics());

        // If in bufferingMode 2, draw to the form's HDC.
        if (bufferingMode == 2) {
            // Render the graphics buffer to the form's HDC.
            grafx.Render(this.get_Handle());
        }
        // If in bufferingMode 0 or 1, draw in the paint method.
        else {
            this.Refresh();
        }
    } //OnTimer

    private void OnResize(Object sender, EventArgs e)
    {
        // Re-create the graphics buffer for a new window size.
        context.set_MaximumBuffer(new Size(this.get_Width() + 1, 
            this.get_Height() + 1));
        if (grafx != null) {
            grafx.Dispose();
            grafx = null;
        }
        grafx = context.Allocate(this.CreateGraphics(), 
            new Rectangle(0, 0, this.get_Width(), this.get_Height()));

        // Cause the background to be cleared and redraw.
        count = 6;
        DrawToBuffer(grafx.get_Graphics());
        this.Refresh();
    } //OnResize

    private void DrawToBuffer(Graphics g)
    {
        // Clear the graphics buffer every five updates.
        if (++count > 5) {
            count = 0;
            grafx.get_Graphics().FillRectangle(Brushes.get_Black(), 0, 0, 
                this.get_Width(), this.get_Height());
        }

        // Draw randomly positioned and colored ellipses.
        Random rnd = new Random();
        for (int i = 0; i < 20; i++) {
            int px = rnd.Next(20, this.get_Width() - 40);
            int py = rnd.Next(20, this.get_Height() - 40);
            g.DrawEllipse(new Pen(Color.FromArgb(rnd.Next(0, 255), 
                rnd.Next(0, 255), rnd.Next(0, 255)), 1), px, py, 
                px + rnd.Next(0, this.get_Width() - px - 20), 
                py + rnd.Next(0, this.get_Height() - py - 20));
        }

        // Draw information strings.
        g.DrawString("Buffering Mode: " 
            + bufferingModeStrings.get_Item(bufferingMode), 
            new Font("Arial", 8), Brushes.get_White(), 10, 10);
        g.DrawString("Right-click to cycle buffering mode", 
            new Font("Arial", 8), Brushes.get_White(), 10, 22);
        g.DrawString("Left-click to toggle timed display refresh",
            new Font("Arial", 8), Brushes.get_White(), 10, 34);
    } //DrawToBuffer

    protected void OnPaint(PaintEventArgs e)
    {
        grafx.Render(e.get_Graphics());
    } //OnPaint

    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        Application.Run(new BufferingExample());
    } //main
} //BufferingExample


System.Object
  System.Drawing.BufferedGraphics

The BufferedGraphics class is not thread safe.Quando estiver acessando um buffer de elementos gráficos de Threads separados, é importante usar um mecanismo de Controlarar de Thread-acesso para evitar conflitos.

Contribuições da comunidade

ADICIONAR
Mostrar:
© 2014 Microsoft