.net 绘制椭圆使用了太多的内存

.net 绘制椭圆使用了太多的内存,.net,vb.net,graphics,gdi+,ram,.net,Vb.net,Graphics,Gdi+,Ram,我想在鼠标移动时画椭圆。这是我的代码 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

我想在鼠标移动时画椭圆。这是我的代码

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
具有相同的图片。

您不需要创建位图来获取图形对象引用

与此相反:

Dim flag As New Bitmap(PictureBox2.Image)
Dim g As Graphics = Graphics.FromImage(flag)
试试这个

Dim g As Graphics = PictureBox2.CreateGraphics
但是,;你真正应该做的是在你需要绘制的picturebox的绘制事件中处理绘画


当鼠标移动时,您存储要绘制的椭圆的坐标,并调用
PictureBox2。无效
,这将导致绘制事件触发。

那么如何设置
PictureBox1.Image
up
g
PictureBox1.Image=g
不工作。
PictureBox1.Image=PictureBox2.Image
?它使用旧图形并绘制许多椭圆。输出是经过设计的。如果要绘制新图形,需要在绘制elipseClear之前调用
g.Clear
:清除整个绘图表面并用指定的背景色填充。(来自msdn)如果PictureBox1.Image不是空的,则调用PictureBox1.Image.Dispose()。并使用Using语句确保图形对象已被释放。