May 9, 2007

Double Buffering in C# .Net

Double Buffering in Dot Net 2.0
More Double Buffering in Dot Net 2.0 - Check this out as well
bool m_Dirty = true;
Bitmap m_Bitmap;

~XXXCtrl()
{
    Dispose(false);
}

public void ChangeSomething(int xmin, int xmax)
{
    ...
    Dirty = true; // Regenerate the bitmap (during the paint cycle)
    Invalidate(); // Repaint
}


protected override void OnResize(EventArgs e)
{
    _DisposeBitmap();
    if ((ClientSize.Width > 0) && (ClientSize.Height > 0))
    {
        m_Bitmap = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);
    }
    else
    {
        m_Bitmap = null;
    }
    Dirty = true;
    base.OnResize(e);
    Invalidate();
}


protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
    Graphics gfx = e.Graphics;
    if (Dirty) 
    { // Only regenerate the bitmap when something has changed
        _RenderToBitmap();
        Dirty = false;
    }
    // Option 1:  Redraw entire bitmap
    //gfx.DrawRectangle(Pens.Red, e.ClipRectangle);
    //_DisplayBitmap(gfx, BitmapRect()); //
    // OR 
    // Option 2:  Redraw just the area that has changed           
    //Debug.WriteLine("Paint: e.ClipRectangle=" +
e.ClipRectangle.ToString());
    _DisplayBitmap(gfx, e.ClipRectangle); 
}


private void _DisplayBitmap(Graphics gfx, Rectangle clipRectangle)
{
    gfx.DrawImage(m_Bitmap, clipRectangle, clipRectangle, GraphicsUnit.Pixel);
}

// Draw the graphics onto a bitmap
private void _RenderToBitmap()
{
    using (Graphics gs = Graphics.FromImage(m_Bitmap))
    {
      _Render(gs, BitmapRect());
    }
}

private Rectangle BitmapRect()
{
    return new Rectangle(0, 0, m_Bitmap.Width, m_Bitmap.Height);
}

// Here is the main graphics routine
private void _Render(Graphics ds, Rectangle area)
{
    // Draw rectangle around client rectangle and text in centre
    Rectangle rect = area;
    rect.Height -= 1;
    rect.Width -= 1;
    using (Brush brush = new SolidBrush(this.BackColor))
    {
        ds.FillRectangle(brush, rect);
    }
    ds.DrawRectangle(Pens.Black, rect);

    if ((area.Width > 25) && (area.Height > 10))
    {
        int xpos = 0;
        // Draw axis
        int x1 = area.Left + 20;
        int x2 = area.Right - 20;
        int ymid = (area.Height/2);
        ds.DrawLine(Pens.Black, new Point(x1, ymid), new Point(x2, ymid));

        ...        
    }
}

private bool Dirty
{
    get { return m_Dirty; }
    set { m_Dirty = value; }
}

private void _DisposeBitmap()
{
    if (m_Bitmap != null)
    {
        m_Bitmap.Dispose();
    }
}

and in the designer class

protected override void Dispose(bool disposing)
{
  if (disposing && (components != null))
  {
     components.Dispose();
  }

  _DisposeBitmap();

  base.Dispose(disposing);
}

No comments: