0

我已经为一些完全由用户绘制的 .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 方法绘制它的标题。

4

1 回答 1

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 对象执行您想要的操作,该对象将绘制到缓冲区而不是屏幕上。

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

于 2014-08-14T19:13:05.430 回答