Creating filled Squares inside Picturboxes with customly made brushes and extracted from a list

64 Views Asked by At

So to explain what my problem is, I made a PictureBox, and I need to fill in many FILLED squares inside of it. However, to do so I would need to create a brush and all of the solutions I've found online are returned as errors by Visual Studio 2019. I don't know what to do anymore.

Here's an example for brush declaration:

SolidBrush shadowBrush = new SolidBrush(customColor) (returns error)


Brush randomBrush = new brush(customColor) (returns error)
1

There are 1 best solutions below

1
On

The way GDI+ drawing works, you should store all the data that represents your drawing in one or more fields and then read that data in the Paint event handler of the appropriate control to do the drawing. In your case, you need information to represent a square and the colour it will be drawn in and you need multiple of them. In that case, you should define a type that has a Rectangle property and a Color property and store a generic List of that type. You can then loop through that list, create a SolidBrush with the Color and call FillRectangle.

Public Class Form1

    Private ReadOnly boxes As New List(Of Box)

    Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
        For Each box In boxes
            Using b As New SolidBrush(box.Color)
                e.Graphics.FillRectangle(b, box.Bounds)
            End Using
        Next
    End Sub

End Class

Public Class Box

    Public Property Bounds As Rectangle

    Public Property Color As Color

End Class

Now, to add a square, you simply create a new Box object, add it to the List and then call Invalidate on the PictureBox. For simplicity, you can call Invalidate with no arguments and the whole PictureBox will be repainted. It is better if you can specify the area that has or may have changed though, because that keeps the repainting, which is the slow part, to a minimum. As you already have a Rectangle that describes the area that has changed, you can pass that, e.g.

Dim boxBounds As New Rectangle(10, 10, 100, 100)

boxes.Add(New Box With {.Bounds = boxBounds, .Color = Color.Black})

PictureBox1.Invalidate(boxBounds)