双缓冲C#

LmS*_*SNe 5 c# graphics doublebuffered

我正在尝试实现以下方法:void Ball :: DrawOn(Graphics g);

该方法应该绘制球的所有先前位置(存储在队列中)并最终绘制当前位置.我不知道这是否重要,但我使用g.DillEllipse(...)打印以前的位置,使用g.FillEllipse(...)打印当前位置.

问题是,你可以想象有很多绘图要做,因此显示开始闪烁很多.我曾寻找过双缓冲的方法,但我能找到的就是这两种方式:

1)System.Windows.Forms.Control.DoubleBuffered = true;

2)SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint,true);

在尝试使用第一个时,我得到一个错误,解释说在此方法中,由于其保护级别,属性DoubleBuffered无法访问.虽然我无法想象如何使用SetStyle方法.

是否有可能将缓冲区加倍,而我拥有的所有访问权限都是我在方法中输入的图形对象?

提前致谢,

编辑:我创建了以下类

namespace doubleBuffer
{
    class BufferedBall : System.Windows.Forms.Form{
        private Ball ball;
        public BufferedBall(Ball ball)
        {
            this.ball = ball;
        }

    public void DrawOn(Graphics g){
        this.DoubleBuffered = true;
        int num = 0;
        Rectangle drawArea1 = new Rectangle(5, 35, 30, 100);
        LinearGradientBrush linearBrush1 =
        new LinearGradientBrush(drawArea1, Color.Green, Color.Orange, LinearGradientMode.Horizontal);
        Rectangle drawArea2 = new Rectangle(5, 35, 30, 100);
        LinearGradientBrush linearBrush2 =
           new LinearGradientBrush(drawArea2, Color.Black, Color.Red, LinearGradientMode.Vertical);
        foreach (PointD point in ball.previousLocations)
        {
            Pen myPen1;
            if (num % 3 == 0)
                myPen1 = new Pen(Color.Yellow, 1F);
            else if (num % 3 == 1)
                myPen1 = new Pen(Color.Green, 2F);
            else
                myPen1 = new Pen(Color.Red, 3F);
            num++;
            myPen1.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
            myPen1.StartCap = System.Drawing.Drawing2D.LineCap.RoundAnchor;
            myPen1.EndCap = System.Drawing.Drawing2D.LineCap.AnchorMask;
            g.DrawEllipse(myPen1, (float)(point.X - ball.radius), (float)(point.Y + ball.radius), (float)(2 * ball.radius), (float)(2 * ball.radius));
        }
        if ((ball.Host.ElapsedTime * ball.Host.FPS * 10) % 2 == 0){
            g.FillEllipse(linearBrush1, (float)(ball.Location.X - ball.radius), (float)(ball.Location.Y + ball.radius), (float)(2 * ball.radius), (float)(2 * ball.radius));
        }else{
            g.FillEllipse(linearBrush2, (float)(ball.Location.X - ball.radius), (float)(ball.Location.Y + ball.radius), (float)(2 * ball.radius), (float)(2 * ball.radius));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

球drawOn看起来像这样:

new BufferedBall(this).DrawOn(g);
Run Code Online (Sandbox Code Playgroud)

这是你的意思吗?因为它还在闪烁?

And*_*rey 4

Form类具有公开为受保护的 DoubleBuffered 属性。http://msdn.microsoft.com/en-us/library/system.windows.forms.control.doublebuffered.aspx,但由于您从中派生表单,因此Form可以使用它。

  • 是的,但你是从 Form 派生的。就像当您创建基本的 winforms 应用程序时一样,它会创建来自 Form 的 Form1。您可以从那里访问它。如果没有 - 您始终可以创建公开此属性的包装器。 (2认同)