Search code examples
.netwinformsdrawing

Drawing layers in GDI


I am creating an application in .NET using winforms. That application must draw on a Panel.

Is it possible to paint objects on different layers, and combine that to one image on the panel? One layer has many objects on it.

sample image


Solution

  • Yes, use a Bitmap for each "layer" and the draw each bitmap to the panel.

    You can control which "layer" is on top by making the calls to DrawImage in a specific order.

    For example:

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
       Bitmap bmp1 = new Bitmap(panel1.Width, panel1.Height);
       Bitmap bmp2 = new Bitmap(panel1.Width, panel1.Height);
    
       Graphics g1 = Graphics.FromImage(bmp1);
       Graphics g2 = Graphics.FromImage(bmp2);
    
       g1.FillRectangle(Brushes.Red, 10, 10, 100, 100);
       g2.FillEllipse(Brushes.Blue, 20, 20, 100, 100);
    
       e.Graphics.DrawImage(bmp1, 0, 0);
       e.Graphics.DrawImage(bmp2, 0, 0);
    }