gpt4 book ai didi

c# - BufferedGraphics 闪烁

转载 作者:行者123 更新时间:2023-11-30 18:46:50 44 4
gpt4 key购买 nike

我尝试实现自定义双缓冲,但它会导致闪烁。

这是控件(继承自Control的自定义控件)构造函数中的代码:

bufferContext = new BufferedGraphicsContext();
SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
SetStyle(ControlStyles.DoubleBuffer, false);
SetStyle(ControlStyles.ResizeRedraw, false);
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
SetStyle(ControlStyles.Opaque, true);

OnPaint 事件:

protected override void OnPaint(PaintEventArgs e)
{
if (buffer == null)
{
Draw(e);
return;
}

if (Repaint)
{
Repaint = false;
PaintEventArgs pe = new PaintEventArgs(buffer.Graphics, e.ClipRectangle);
Draw(pe);
}

buffer.Render(e.Graphics);
}

此外,此代码在与缓冲相关的调整大小时激活:

Graphics g = this.CreateGraphics();

if (buffer != null)
{
buffer.Dispose();
buffer = null;
}

if (!(bufferContext == null || DisplayRectangle.Width <= 0 || DisplayRectangle.Height <= 0))
{
buffer = bufferContext.Allocate(g, DisplayRectangle);
Repaint = true;
}

Draw方法比较复杂,但先用BackColor填充控件,其他无关。

我可以用眼睛发现有时会出现闪烁,主要是在调整窗口大小时。据我所知,首先在控件上绘制黑色,然后从缓冲区绘制图形,这会导致闪烁。但是,BackColor 永远不会是黑色。

如何阻止这种情况?

最佳答案

这个例子展示了如何正确使用 Buffered Graphics:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GDI_PAINTING_EXAMPLE
{
public class PaintingExample : Control
{
public Graphics G;
public Bitmap Frame = new Bitmap(256, 256);
public Bitmap Buffer = new Bitmap(256, 256);

public PaintingExample()
{
// Create a new Graphics instance.
G = Graphics.FromImage(Buffer);
}

protected override void OnPaint(PaintEventArgs e)
{
// Clears Buffer To White
G.Clear(Color.White);



//
// Do Your Painting Routine
//

//
// End Your Painting Routine
//



// Set Frame to draw as Buffer
Frame = Buffer;

// Draw Frame with Paint Event Graphics as one image.
e.Graphics.DrawImage(Frame, new Point(0, 0));
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
}
}
}

关于c# - BufferedGraphics 闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14550095/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com