RotateTransform减慢C#GDI +中的FillRectangle函数?

时间:2012-12-17 16:39:02

标签: c# .net gdi+ rotatetransform

我有一个在屏幕上绘制点的功能。在我添加panelGraphics.RotateTransform行之前,此功能非常有效。当这条线存在时,进行一次重绘的过程非常漫长。我的点列表包含大约5000个点并且没有旋转,它在几毫秒内完成,但是使用该行可能需要500毫秒,这非常慢。您是否知道为什么RotateTransform如此缓慢?我还能做些什么来优化它?

private void panel1_Paint(object sender, PaintEventArgs e)
{
    Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
    SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
    Graphics panelGraphics = panel1.CreateGraphics();

    panelGraphics.TranslateTransform((panel1.Width / 2) + _panW, (panel1.Height / 2) + _panH);

    //Problematic line...
    panelGraphics.RotateTransform(230 - Convert.ToInt32(_dPan), System.Drawing.Drawing2D.MatrixOrder.Prepend);

    PointF ptPrevious = new PointF(float.MaxValue, float.MaxValue);
    foreach (PointF pt in _listPoint)
    {
        panelGraphics.FillRectangle(myBrush, (pt.X / 25) * _fZoomFactor, (pt.Y / 25) * _fZoomFactor, 2, 2);
    }

    myBrush.Dispose();
    myPen.Dispose();
    panelGraphics.Dispose();
}

1 个答案:

答案 0 :(得分:2)

原因是每个矩形都必须旋转。旋转可能是一个缓慢的操作,特别是对于没有方角。

在这种情况下,更好的方法是先创建一个“隐藏”的位图,然后将矩形绘制成。 然后将旋转应用于主图形对象,并将隐藏的位图绘制到主位图(控件)上。像这样的东西 -

private void panel1_Paint(object sender, PaintEventArgs e)
{
    Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Red);
    SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);

    Graphics panelGraphics = e.Graphics; //use the provided Graphics object

    // create an internal bitmap to draw rectangles to
    Bitmap bmp = new Bitmap(this.ClientSize.Width, _
                            this.ClientSize.Height, _
                            Imaging.PixelFormat.Format32bppPArgb);

    using (Graphics g = Graphics.FromImage(bmp)) {

        PointF ptPrevious = new PointF(float.MaxValue, float.MaxValue);
        foreach (PointF pt in _listPoint) {
            g.FillRectangle(myBrush, (pt.X / 25) * _fZoomFactor, _
                                     (pt.Y / 25) * _fZoomFactor, 2, 2);
        }   
    }

    panelGraphics.TranslateTransform((panel1.ClientSize.Width / 2) + _panW, _
                                     (panel1.ClientSize.Height / 2) + _panH);

    //Problematic line...
    panelGraphics.RotateTransform(230 - Convert.ToInt32(_dPan), _
                                  System.Drawing.Drawing2D.MatrixOrder.Prepend);

    panelGraphics.DrawImage(bmp, 0, 0); //adjust x/y as needed
    bmp.Dispose;

    myBrush.Dispose();
    myPen.Dispose();
}