2

如何重新绘制平滑的面板?

我正在使用一个计时器,它panel1.Invalidate();每 300 毫秒使面板()无效,然后在panel1_Paint我向该面板添加图像的事件中,问题是它看起来像是在跳跃,我需要像我一样快地在上面移动一个图像能够。

这是截屏问题的链接:http://screencast.com/t/HdtIV99YN

 private void panel1_Paint(object sender, PaintEventArgs e)
            {
                PaintMapObstacles(e);
                PaintMapStartAndGoal(e);

                if (trayectoryIndex < 1000)
                {
                   MapPoint point =  GetTrayectoryPoint(0, trayectoryIndex);
                   e.Graphics.DrawImage(new Bitmap("robot.jpg"), point.X*squareSize, point.Y*squareSize, 60, 60);
                   trayectoryIndex++;
               }
            }
     private void PaintMapStartAndGoal(PaintEventArgs e)
            {
                MapPoint start = new MapPoint { X = 0, Y = 0 };
                MapPoint goal = new MapPoint { X = 7, Y = 8 };
                   // e.Graphics.DrawImage(new Bitmap("start.jpg"), start.X * squareSize, start.Y * squareSize, 60, 60);
                    e.Graphics.DrawImage(new Bitmap("goal.jpg"), goal.X * squareSize, goal.Y * squareSize, 60, 60);
                    isFirstRun = true;
            }


        private void PaintMapObstacles(PaintEventArgs e)
            {

                foreach (MapPoint mpoint in obstacles.Obstacles)
                {
                    e.Graphics.DrawImage(new Bitmap("obstacle.png"), mpoint.X * squareSize, mpoint.Y * squareSize, 60, 60);  
                }
            }

         private void PanelTimer_Tick(object sender, EventArgs e)
            {

                panel1.Invalidate();
            }
4

1 回答 1

3

它被称为“闪烁”,当您从头开始重新绘制窗口时,它总是会出现。这在您的程序中尤其明显,因为您的绘画代码效率很低。您会看到窗口的背景被绘制出来,抹掉了旧画。然后慢慢将位图重新绘制到背景上。擦除步骤肉眼可见,看起来像闪烁。

闪烁的一般解决方法是双缓冲,首先将窗口内容组合成一个位图,然后快速将位图传送到屏幕上。它是 Winforms 的内置功能,DoubleBuffered 属性将其打开。Panel 类默认情况下不启用双缓冲,它被设计为一个容器控件,除了绘制背景之外不会自行绘制。PictureBox 在您的情况下也可以正常工作,默认情况下它启用了双缓冲。或者您可以为 Panel 类打开双缓冲,如下所示

您确实希望最终解决绘画代码的问题,除了它非常慢之外,它还可能使您的程序因 OutOfMemoryException 而崩溃。使用 Bitmap 类的方式导致的问题,使用后应该处理掉。始终对 System.Drawing 对象使用using语句。

通过只创建一次位图,您将使其更快,表单构造函数是最好的地方。您可以通过预缩放位图以适合网格并注意像素格式来使其非常快。PixelFormat.Format32bppPArgb 直接兼容几乎所有现代视频适配器的帧缓冲区格式,位图无需转换即可直接复制到帧缓冲区中。比所有其他格式快十倍。转换代码在这里

于 2014-03-05T23:10:53.197 回答