位图重绘在图片框中滞后

时间:2016-04-16 19:21:02

标签: c# winforms drawing

我有一个应用程序,你可以在其中绘制一些形状,通过顶点捕捉它们并移动顶点。我在List中存储形状的顶点,并在分配给PictureBox.Image的位图中重绘整个对象列表(当顶点是捕捉和鼠标移动时)。当我添加超过5个形状时,移动顶点是滞后的。这是一段代码:

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

如果还有改进呢?我试图graphic.Clear(Color.Transparent)但是没有办法改变位图的大小(当我们调整窗口大小时使用该函数)。

任何提示?

2 个答案:

答案 0 :(得分:0)

我发现了实际上造成滞后的简单错误。 pictureBox2.Image = graphic;连续执行了两次PointsList.Count != 0什么造成了滞后。

答案 1 :(得分:0)

您的代码看起来过于复杂且无效。此外,您的代码过于依赖垃圾收集器(在使用后立即部署GraphicsBrushPen类是一种很好的做法。

我认为在您的情况下,最好的想法是避免完全创建和处理位图。您可以将PictureBox替换为Panel类,订阅其Paint事件并在此方法中绘制形状。当顶点的位置发生变化时,只需调用Invalidate方法重新绘制面板内的形状。