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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…