我正在尝试进行双缓冲来消除闪烁,但重新绘制图像会闪烁。我需要在新位置的酒吧中定期重绘图像,这对我有用。但是重画的时候闪烁很明显。请帮忙。
namespace CockroachRunning
{
public partial class Form1 : Form
{
Random R = new Random();
Semaphore s1 = new Semaphore(2, 4);
Bitmap cockroachBmp = new Bitmap(Properties.Resources.cockroach, new Size(55, 50));
List<Point> cockroaches = new List<Point>();
public Form1()
{
InitializeComponent();
this.DoubleBuffered = true;
cockroaches.Add(new Point(18,13));
Thread t1 = new Thread(Up);
t1.Start();
}
public void Up()
{
while (true)
{
s1.WaitOne();
int distance = R.Next(1, 6);
for (int i = 0; i < distance; i++)
{
if (cockroaches[0].Y - 1 > -1)
{
cockroaches[0] = new Point(cockroaches[0].X, cockroaches[0].Y - 1);
panel1.Invalidate();
}
}
s1.Release();
Thread.Sleep(100);
}
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
Image i = new Bitmap(panel1.ClientRectangle.Width, panel1.ClientRectangle.Height);
Graphics g = Graphics.FromImage(i);
Graphics displayGraphics = e.Graphics;
g.DrawImage(cockroachBmp, cockroaches[0]);
displayGraphics.DrawImage(i, panel1.ClientRectangle);
}
}
}
最佳答案
为了消除闪烁,我使用以下设置来配置控件的行为方式:
base.DoubleBuffered = true;
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
UpdateStyles();
我在 Control
的构造函数中调用它-派生类。我不确定这是否也适用于表单,但我想是的。
然后在void OnPaintBackground(PaintEventArgs e)
(删除客户区域)和void OnPaint(PaintEventArgs e)
(实际绘制)中完成绘制。
关于c# - 如何为面板设置双缓冲?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10720030/