使用双缓冲实现无闪烁图形,以及如何制作简单的图形移动。






3.05/5 (23投票s)
2004年5月13日
2分钟阅读

108551

1789
这个例子将向你展示如何使用双缓冲,并希望能够让你在屏幕上移动图像。
引言
在编写一个我希望以后发布的游戏的期间,我不得不找到一种减少闪烁的方法。我还遇到了重绘导致游戏移动极其缓慢的问题。我做了一些研究,发现了双缓冲、计时器和绘制事件。希望你像我一样从中学到东西。
步骤1:制作计时器
- 在创建基本的 WinForm 框架后,转到工具栏。选择
Timer
并将其拖动到 WinForm 中。 - 右键单击
Timer
并点击“属性”。- 确保
enabled
设置为true
。 - 将
Interval
设置为1
。 - 点击闪电图标(事件生成器)。
- 在看到 tick 的地方,添加一个名为
moveme
的事件。 - 现在,当我们有一个事件时,它将带你到代码块。
- 添加以下内容
if(CarsXValue>0) CarsXValue-=Carspeed; else { CarsXValue=672; } Invalidate();
- 在看到 tick 的地方,添加一个名为
- 确保
步骤2:制作绘制事件
现在我们需要制作一个绘制事件来为我们绘制图像。所以我们这样做
- 在
form1()
构造函数中包含以下内容Paint += new PaintEventHandler(OnPaint);
- 然后你需要通过以下方式实际制作
Onpaint
事件。void OnPaint(Object sender, PaintEventArgs e) { Graphics g = e.Graphics; DrawCar(g); }
- 创建一个
DrawCar
函数来为我们绘制图像void DrawCar(Graphics g) { g.DrawImage(FastCar,CarsXValue,672); //draw the image using the image fastcar //its x value //and a hardcoded y value }
步骤 3:制作我们的变量
现在我们需要一些变量来控制我们的移动。我们还需要一个要绘制的图像和一个 X 坐标,我稍后会解释。
- 在声明所有其他主要变量的地方制作以下变量。
int CarsXValue=0; // x cordinate used for the car int CarSpeed=2; // how fast it will move across the screen Image FastCar=Image.FromFile("fastcar.gif"); // our car image
*****确保 FASTCAR.GIF 在 debug 或 release 文件夹中**********
步骤 4:开启双缓冲
现在我们开启双缓冲以防止闪烁。在 Form1()
构造函数中包含以下代码。你就可以完成了。
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
步骤 5:编译并运行
再次确保 fastcar.gif 在你的 debug 或 release 文件夹中,具体取决于你选择的构建配置。
结论
希望这能像对我一样对你有所帮助。