Question

I am trying to draw a rectangle that has two colours yellow and green using a diaganol split with text in the middle.

The problem is that I want the text in the middle to be white where it is over the green and black when it is over the yellow.

An example here:

enter image description here

I can draw the yellow, green and the text in either black or white, but how can I mask off the text to get the desired effect?

here is my code so far:

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
Was it helpful?

Solution

I have managed to do this by:

  • Creating a temporary bitmap that contains the green background colour with white text.
  • The draw a triangle over one half in a specific colour
  • Then use MakeTransparent() on the bitmap to remove the triangle I just created.
  • I then overlay the new bitmap onto the original square.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top