Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

vb.net - Creating filled Squares inside Picturboxes with customly made brushes and extracted from a list

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)
question from:https://stackoverflow.com/questions/65944479/creating-filled-squares-inside-picturboxes-with-customly-made-brushes-and-extrac

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...