user34537
user34537

Reputation:

How do i draw more efficiently?

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);
    }

Upvotes: 0

Views: 422

Answers (3)

J-16 SDiZ
J-16 SDiZ

Reputation: 26910

Have you enable double buffering?

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

Upvotes: 3

Turnor
Turnor

Reputation: 1856

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

Upvotes: 0

Guffa
Guffa

Reputation: 700152

How about:

void draw(Color c) {
   using (Graphics g = Graphics.FromImage(b)) {
      g.Clear(c);
   }
}

Upvotes: 1

Related Questions