简体   繁体   中英

Bitmap repaint in picturebox lagging

I have application in which you can draw some shapes, catch them by vertices and move the vertice. I store vertices of a shapes in the List and repaint whole list of the objects (when the vertice is catch and mouse moves)in the bitmap which is assigned to PictureBox.Image . When I add more than 5 shapes, the moving vertice is lagging. Here is a piece of code:

    private void DrawFullList()
    {
        if (pictureBox2.Image != null)
        {
            pictureBox2.Image.Dispose();
            g.Dispose();
        }
        graphic = new Bitmap(pictureBox2.Width, pictureBox2.Height);
        g = Graphics.FromImage(graphic);
        pictureBox2.Image = graphic;
        for (int i = 0; i < PointsList.Count; i++)
            Draw(BrushList[i], PointsList[i]);
    }
    private void Draw(Brush brush, Point[] points)
    {
        Pen PathPen = new Pen(brush);
        PathPen.Width = 3;
        if (points.Length == 2)
            g.DrawLine(PathPen, points[0], points[1]);
        else
            g.FillPolygon(brush,points);
        pictureBox2.Image = graphic;
    }

If there anyway to imporve it? I was trying to graphic.Clear(Color.Transparent) but there was no way to change the size of bitmap ( the function is used when we resizing the window).

Any tips?

I found simple mistake what actually makes the lags. pictureBox2.Image = graphic; was executed two times in a row, when PointsList.Count != 0 what was creating laggs.

Your code looks overcomplicated and ineffective. Also your code rely too hard on garbage collector (it is a good practice to dispose Graphics , Brush and Pen classes right after use).

I think in your case best idea is to avoid creating and disposing bitmaps completely. You can replace your PictureBox with, for example, Panel class, subscribe to its Paint event and paint your shapes inside this method. When position of your vertices changes simply call Invalidate method to repaint your shapes inside panel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM