tags:

views:

98

answers:

3

How do i draw this more efficiently?

I can feel the lag when i call the code below. NOTE this is about pixel editing and not clearing the screen.

    int colorIndex = 0;
    private void pictureBox1_Click(object sender, EventArgs e)
    {
        if (colorIndex == 0)
            draw(Color.DimGray);
        else if(colorIndex ==1)
            draw(Color.ForestGreen);
        colorIndex++;
        colorIndex = colorIndex % 2;

        pictureBox1.Invalidate();
        //pictureBox1.Update();
    }

    void draw(Color c)
    {
        //var bdata = b.LockBits(Rectangle.Empty, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        //var px = bdata.Scan0;
        var px = b;
        {
            for (int y = 0; y < b.Height; y++)
            {
                for (int x = 0; x < b.Width; x++)
                    //px[y * b.Width + x] = -1;
                    px.SetPixel(x, y, c);
            }
        }
        //b.UnlockBits(bdata);
    }
+1  A: 

How about:

void draw(Color c) {
   using (Graphics g = Graphics.FromImage(b)) {
      g.Clear(c);
   }
}
Guffa
my question is about pixel access and not about clearing the screen. (edit question)
acidzombie24
The code is not clearing the screen, it's setting every pixel in the Bitmap object to the specified color. Exactly the same as what your code is doing, only a lot faster.
Guffa
A: 

SetPixel/GetPixel are generally slow operations. If you can use unsafe code (code which uses pointers), there are faster methods of access, but they're slightly more involved. There is a tutorial here which explains how it works, however:

http://www.codeproject.com/KB/GDI-plus/csharpgraphicfilters11.aspx

Turnor
+1  A: 

Have you enable double buffering?

btw, If you are just drawing rectangle, you can use the DrawRectangle method.

J-16 SDiZ