这个Region.Exclude行为是否正确?

时间:2012-08-22 15:19:48

标签: .net winforms graphics gdi

我有一个System.Drawing.Region对象,其中GetBounds()方法返回

  

{X = 0.0 Y = 0.0宽度= 120.0高度= 120.0}

但是当我用矩形执行Exclude()方法时:

region.Exclude(New System.Drawing.Rectangle(60, -20, 100, 160))

我希望Region.GetBounds方法返回

  

{X = 0.0 Y = 0.0宽度= 60.0高度= 120.0}

而是Exclude()调用似乎什么都不做。与Intersect()方法类似

region.Intersect(New System.Drawing.Rectangle(60, -20, 100, 160))

我希望看到

  

{X = 60.0 Y = 0.0宽度= 60.0高度= 120.0}

但同样没有变化。这是对的吗?

修改:特定背景

我正在一个大型项目上使用OnPaintBackground()方法,在基本Control的方向上具有一般透明度:What is a general solution to creating a transparent control?

Protected Overrides Sub OnPaintBackground(pevent As System.Windows.Forms.PaintEventArgs)
    Dim initialClip As Region = pevent.Graphics.Clip

    'Develop list of underlying controls'
    Dim submarinedControls As New List(Of Control)
    For Each control As Control In Parent.Controls.ToArray.Reverse
        If control IsNot Me AndAlso control.Visible AndAlso Me.ClientRectangle.IntersectsWith(control.RelativeClientRectangle(Me)) Then : submarinedControls.Add(control)
        Else : Exit For
        End If
    Next

    'Prepare clip for parent draw'
    pevent.Graphics.Clip = New Region(initialClip.GetRegionData)
    For Each control As Control In submarinedControls
        pevent.Graphics.Clip.Exclude(control.RelativeClientRectangle(Me))
    Next

    ...
End Sub

在“准备父级重绘的剪辑”部分中,在重新创建初始剪辑后,其边界与指定的一样。下一步是排除任何基础控件,并仅绘制此控件直接与父控件背景交互的区域。我在这里看到的排除方法是接收较大的矩形作为其参数(作为Watch),但是在排除发生之后,没有任何关于剪辑边界的变化。

修改:可能的解决方案

Graphics.Clip区域似乎由Graphics对象管理,并且是不可变的。使用以下内容替换排除代码段会产生所有预期结果:

    'Prepare clip for parent draw'
    Dim parentClip As System.Drawing.Region = New System.Drawing.Region(initialClip.GetRegionData)
    For Each Control As Control In submarinedControls
        parentClip.Exclude(Control.RelativeClientRectangle(Me))
    Next
    pevent.Graphics.Clip = parentClip

RelativeClientRectangle():

<Runtime.CompilerServices.Extension()>
Public Function RelativeClientRectangle(control As System.Windows.Forms.Control, toControl As System.Windows.Forms.Control) As System.Drawing.Rectangle
    Return New System.Drawing.Rectangle(control.RelationTo(toControl), control.Size)
End Function

对于relativeTo():

<Runtime.CompilerServices.Extension()>
Public Function RelationTo(control As System.Windows.Forms.Control, toControl As System.Windows.Forms.Control) As System.Drawing.Point
    Return control.PointToScreen(New Point(0, 0)) - toControl.PointToScreen(New Point(0, 0))
End Function

1 个答案:

答案 0 :(得分:0)

虽然我无法确定,但所有工作似乎都同意我的最终编辑,即Graphics.Clip的管理比孤儿区域更严格。在离线准备区域进行修改时,完全解决了观察到的行为。