简体   繁体   English

图片框滞后的位图重绘

[英]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 . 我将形状的顶点存储在List并在分配给PictureBox.Image的位图中重新绘制对象的整个列表(当顶点为catch和鼠标移动时)。 When I add more than 5 shapes, the moving vertice is lagging. 当我添加5个以上的形状时,移动的顶点滞后。 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). 我正在尝试graphic.Clear(Color.Transparent)但是无法更改位图的大小(在调整窗口大小时使用该函数)。

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. 连续执行两次,当PointsList.Count != 0会导致滞后。

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). 另外,您的代码过于依赖垃圾回收器(在使用后立即处置GraphicsBrushPen类是一种很好的做法)。

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. 您可以将PictureBox替换为例如Panel类,订阅其Paint事件并在此方法内绘制形状。 When position of your vertices changes simply call Invalidate method to repaint your shapes inside panel. 当顶点位置改变时,只需调用Invalidate方法即可在面板内重新绘制形状。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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