如何使用GDI +绘图时屏蔽区域

时间:2013-08-27 09:11:01

标签: .net winforms graphics gdi+ masking

我正在尝试绘制一个黄色和绿色两种颜色的矩形,使用中间带有文本的diaganol分割。

问题在于我希望中间的文字在绿色和黑色之上是白色的,当它在黄色上时。

这里有一个例子:

enter image description here

我可以用黑色或白色绘制黄色,绿色和文字,但是如何屏蔽文字以获得所需的效果呢?

到目前为止,这是我的代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim colour1Brush As New SolidBrush(Color.Yellow)
    Dim colour2Brush As New SolidBrush(Color.Green)
    Dim g As Graphics = Me.CreateGraphics
    Dim rect As New Rectangle(New Point(50, 50), New Size(100, 50))
    With g
        'draw the background yellow
        .FillRectangle(colour1Brush, rect)
        'put in the black text
        DrawText(g, rect, "12", Brushes.Black)
        'draw the green triangle
        Dim triPoints(2) As Point
        triPoints(0) = New Point(rect.Left + rect.Width, rect.Top)
        triPoints(1) = New Point(rect.Left + rect.Width, rect.Top + rect.Height)
        triPoints(2) = New Point(rect.Left, rect.Top + rect.Height)
        .FillPolygon(colour2Brush, triPoints)
        'now we need white text that doesn't overwrite the existing black text
        '?????? DrawText(g, rect, "12", Brushes.White)
    End With
End Sub

Private Sub DrawText(ByRef g As Graphics, ByVal rect As Rectangle, ByVal text As String, ByVal brush As Brush)
    Dim fnt As New Font("Segoe UI", 8)
    Dim textSize As SizeF = g.MeasureString(text, fnt)
    Dim x As Integer = CInt(rect.Left + ((rect.Width / 2) - (textSize.Width / 2)))
    Dim y As Integer = CInt(rect.Height + ((rect.Height / 2) - (textSize.Height / 2)))
    g.DrawString(text, fnt, brush, New Point(x, y))
End Sub

1 个答案:

答案 0 :(得分:0)

我设法通过以下方式做到了这一点:

  • 创建包含带有白色文本的绿色背景颜色的临时位图。
  • 以特定颜色绘制一半的三角形
  • 然后在位图上使用MakeTransparent()删除我刚刚创建的三角形。
  • 然后我将新位图叠加到原始方块上。