有谁知道如何摆脱闪烁?我研究了 SO,网络,并尝试了许多不同的事情,例如在不绘制 OnPaint() 时将 TickerControl 放入双缓冲面板中,例如双缓冲:为什么它不起作用?等等。除了许多其他的事情。它仍然闪烁,不是在每次重新绘制时,而是每秒几次。
此外,即使在 OnPaint 中删除“g.Clear(BackColor)”之后,仍然必须清除背景,因为文本继续以可读的方式滚动。
这里是我的 TickerControl 类的相关部分:
class TickerControl : Control
{
private static readonly StringFormat stringFormat = new StringFormat(StringFormatFlags.NoWrap);
private const int padding = 40;
private const int scrollSleep = 10;
private const int scrollAdvancePixels = 1;
private float textWidth;
private float currentX;
private static readonly Timer scrollTimer = new Timer();
public TickerControl()
{
this.SetStyle(ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer
, true);
scrollTimer.Tick += AdvanceText;
scrollTimer.Interval = scrollSleep;
scrollTimer.Enabled = true;
}
private void AdvanceText(object sender, EventArgs e)
{
if (IsDisposed)
return;
currentX -= scrollAdvancePixels;
if (currentX <= -textWidth)
currentX = 0;
Invalidate();
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.Clear(BackColor);
using (SolidBrush brush = new SolidBrush(ForeColor))
{
g.DrawString(Text, Font, brush, currentX, 0, stringFormat);
g.DrawString(Text, Font, brush, currentX + textWidth, 0, stringFormat);
}
}
有任何想法吗?
更新:
正如sallushan 建议的手动双缓冲,让我补充一下,我之前已经尝试过,使用下面的代码。但在屏幕上它看起来与上面完全一样,所以问题似乎并不在于我的 OnPaint 方法。我想它一定在我的控件设置中的某个地方。
private Bitmap backBuffer;
protected override void OnPaint(PaintEventArgs e)
{
if (backBuffer == null)
backBuffer = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);
Graphics g = Graphics.FromImage(backBuffer);
g.Clear(BackColor);
using (SolidBrush brush = new SolidBrush(ForeColor))
{
g.DrawString(Text, Font, brush, currentX, 0, stringFormat);
g.DrawString(Text, Font, brush, currentX + textWidth, 0, stringFormat);
}
g.Dispose();
e.Graphics.DrawImageUnscaled(backBuffer, 0, 0);
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
// Don't call base!
}
protected override void OnSizeChanged(EventArgs e)
{
if (backBuffer != null)
{
backBuffer.Dispose();
backBuffer = null;
}
base.OnSizeChanged(e);
}