我正在尝试在图片框上创建一个带有randome大小和位置的矩形。每次用户点击按钮时,该矩形将被删除,并且将显示新的矩形。
Private Sub btnDraw_Click(sender As Object, e As EventArgs) Handles btnDraw.Click
RandomBox()
End Sub
Public Sub RandomBox()
Dim r As New Rectangle(CInt(Rnd() * picGene.Width), CInt(Rnd() * picGene.Height), 20 + Rnd() * 50, 10 + Rnd() * 50)
Dim g As System.Drawing.Graphics
g = picGene.CreateGraphics()
g.FillRectangle(Brushes.Blue, r)
End Sub
它始终保留先前绘制的矩形,因此我尝试在代码块之前或之后放置picGene.Invalide()。它会删除旧的矩形,但不会绘制新的矩形。
Public Sub RandomBox()
picGene.Invalidate()
Dim r As New Rectangle(CInt(Rnd() * picGene.Width), CInt(Rnd() * picGene.Height), 20 + Rnd() * 50, 10 + Rnd() * 50)
Dim g As System.Drawing.Graphics
g = picGene.CreateGraphics()
g.FillRectangle(Brushes.Blue, r)
'picGene.Invalidate()
End Sub
有什么想法吗?
由于
答案 0 :(得分:1)
将一个Rectangle存储在内存中,每次单击都要更改一个Rectangle,然后在paint事件中绘制它。对于随机生成的值,Random
类是最好的选择。
Private rect As New Rectangle
Private Sub btnDraw_Click(sender As Object, e As EventArgs) Handles btnDraw.Click
Static rnd As New Random
rect = New Rectangle(rnd.Next(picGene.Width), rnd.Next(picGene.Height), 20 + rnd.Next({somevalue}) * 50, 10 + rnd.Next({someValue}) * 50)
pb.Refresh() 'redraw the rectangle
End Sub
Private Sub picGene_Paint(sender As Object, e As PaintEventArgs) Handles picGene.Paint
e.Graphics.DrawRectangle(Pens.Black, rect)
End Sub