c# Winforms使用拖线方法进行屏幕的超慢更新



我已经在网上看了一下,但还没有找到我正在寻找的确切答案,或者我已经尝试了建议的内容,但它不起作用!

我有一个问题,我有一个屏幕上有大约72个复选框在一个矩阵中,我用线连接在一起,我存储在一个列表中的坐标。

为了绘制线条,我在OnPaint的覆盖方法中使用Drawline方法来迭代列表,如下所示:

protected override void OnPaint(PaintEventArgs e)
    {
        Pen myPen = new Pen(System.Drawing.Color.Black);
        Graphics g = this.CreateGraphics();
        myPen.Width = 5;
       foreach(ConnectionLine cl in connectionLines)
       {
        g.DrawLine(myPen, cl.xStart, cl.yStart, cl.xStop, cl.yStop);
       }
        myPen.Dispose();
        g.Dispose();
    }

奇怪的是,它似乎不需要花费时间来绘制线条-现在是复选框,如果我删除线条功能,这些刷新在眨眼之间。

如有任何建议,不胜感激。

谢谢,戴夫

部分问题可能是每次绘制控件时都要重新创建Graphics对象。相反,您应该使用PaintEventArgs中提供的e.Graphics对象。您也可以尝试只使用一个Pen实例。

 private readonly Pen _myPen = new Pen(System.Drawing.Color.Black) {Width = 5};
 protected override void OnPaint(PaintEventArgs e)
 {
     foreach (var cl in connectionLines)
         e.Graphics.DrawLine(_myPen, cl.xStart, cl.yStart, cl.xStop, cl.yStop);
 }

不需要创建自己的图形对象并处理它。使用事件处理程序中可用的内容。另外,你应该使用using而不是显式地调用Dispose。

    protected override void OnPaint(PaintEventArgs e)
    {
        using (Pen myPen = new Pen(System.Drawing.Color.Black, 5.0))
        {
           foreach(ConnectionLine cl in connectionLines)
                   e.Graphics.DrawLine(myPen, cl.xStart, cl.yStart, cl.xStop, cl.yStop);
        }
    }

同样,如果你的线连接,你应该得到更好的性能和更干净的代码与图形的DrawLines方法。在调用之前,您必须更改存储点的方式或从connectionlines集合中提取点。

最新更新