我想在鼠标移动时绘制椭圆。这是我的代码
Dim released As Boolean = False
Dim firstx As Integer = 0
Dim firsty As Integer = 0
Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseMove
If e.Button = MouseButtons.Left Then
If released = False Then
firstx = e.X
firsty = e.Y
released = True
End If
Dim flag As New Bitmap(PictureBox2.Image) 'This code fills RAM everytime.
Dim g As Graphics = Graphics.FromImage(flag)
g.DrawEllipse(New Pen(Color.MediumOrchid, 5), firstx, firsty, e.X - firstx, e.Y - firsty)
g.Dispose()
PictureBox1.Image = flag
Else
released = False
End If
End Sub
我知道在MouseMove
事件中定义图形会导致这个问题。它会在每一个动作中创建图形。解决方案是什么?
注意: PictureBox1
和PictureBox2
具有相同的图片。
答案 0 :(得分:1)
您不需要为创建位图来获取图形对象引用的开销。
而不是:
Dim flag As New Bitmap(PictureBox2.Image)
Dim g As Graphics = Graphics.FromImage(flag)
试试这个
Dim g As Graphics = PictureBox2.CreateGraphics
然而;你应该做的是在你需要绘制的图片框的绘画事件中处理绘画。
当鼠标移动时,您存储要绘制的椭圆的坐标并调用PictureBox2.Invalidate
,这将导致绘制事件。