在基础控件上绘制时,.NET CF双缓冲

时间:2014-08-13 19:57:04

标签: .net compact-framework double-buffering

我对一些完全由用户绘制的.NET Compact Framework控件使用了双缓冲,但是我无法弄清楚如何使用双缓冲来控制从另一个控件继承的控件它

我有一个基于DataGrid的控件,它描绘了标题。

我的OnPaint方法是:

Protected Overrides Sub OnPaint(ByVal pe as System.Windows.Forms.PaintEventArgs)
    MyBase.OnPaint(pe)
    CustomPaintHeaders(pe.Graphics)
End Sub

CustomPaintHeaders只是使用一些自定义绘图在基本DataGrid标题上绘制。偶尔,我会看到基本的DataGrid标题被绘制的地方闪烁,但没有我自定义绘制的东西。

是否可以使用双缓冲,并将MyBase.OnPaint完成的绘画应用于缓冲区图像?

编辑:正如我的评论所述,我可以使用此代码进行双缓冲:

Protected Overrides Sub OnPaint(ByVal pe as System.Windows.Forms.PaintEventArgs)
    Using currentRender as Bitmap = New Bitmap(Me.Width, Me.Height)
        Using gr as Graphics = Graphics.FromImage(currentRender)
            CustomPaintHeaders(gr)
            CustomPaintRows(gr)
        End Using
    End Using
End Sub

Private Sub CustomPaintHeaders(ByVal graphics as Graphics)

    'Custom drawing stuff in place of DataGrid column headers

End Sub

'TEMP - draws rectangle in place of grid rows
Private Sub CustomPaintRows(ByVal graphics as Graphics)
    graphics.DrawRectangle(New Pen(Me.ForeColor), 0, 20, Me.Width, Me.Height) 
End Sub

这样可以正常工作而不会闪烁,但我想避免实现CustomPaintRows,只需让DataGrid的OnPaint为我处理该部分,然后用我的CustomPaintHeaders方法绘制它的标题。

1 个答案:

答案 0 :(得分:0)

CF中的双缓冲是一个手动过程,所以我假设您的基类包含它正在绘制的图像或位图?这取决于你是如何进行绘画的,但你可以制作图像protected,或者你可以做一些稍微复杂的事情:

protected virtual void OnPaint(graphics bufferGraphics) { } 

void OnPaint(PaintEventArgs pe)
{
    var buffer = new Bitmap(this.Width, this.Height);
    var bufferGraphics = Graphics.FromImage(buffer);

    // do base painting here
    bufferGraphics.DrawString(....);
    // etc.

    // let any child paint into the buffer
    OnPaint(bufferGraphics);

    // paint the buffer to the screen
    pe.Graphics.DrawImage(buffer, 0, 0);
}

然后在您的孩子中,只需覆盖新的OnPaint并使用传入的Graphics对象执行您想要的操作,该对象将绘制到缓冲区而不是屏幕上。

如果您希望孩子能够完全覆盖基础绘画,只需将基础绘制逻辑移动到虚拟方法中。

相关问题