PictureBox2.Image = PictureBox1.Image似乎是在链接框而不是复制图像?

时间:2019-01-13 11:33:35

标签: vb.net

问题

我有一个带有2个PictureBoxes的简单表单

我允许用户在 PictureBox1 上绘画 当我单击表单上的 Butto n时,我想在 PictureBox1 中捕获图像并将其存储在 PictureBox2

问题是,如果我添加以下行:      PictureBox2.Image = PictureBox1.Image PictureBox1 的任何更新都会立即反映在 PictureBox2 吗?!?

我只想及时在 PictureBox1 中捕获图像,以便可以将其用于“撤消”

技术

这是使用Visual Studio 2019预览版的Visual Basic.net 4.7.2中的Windows窗体应用程序

代码

Public Class Form1

    Dim drawMouseDown = False ' Set initial mouse state to not clicked
    Dim drawMyBrush As New Pen(Brushes.White, 20) 'Set up the Brush
    Public drawCanvas As New Bitmap(245, 352) 'Set up Bitmap Canvas

    Private Sub btn_Color_Yellow_Click(sender As Object, e As EventArgs) Handles btn_Color_Yellow.Click
        drawMyBrush.Brush = Brushes.Yellow
        drawMyBrush.Width = 20
    End Sub

    Private Sub PictureBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseDown
        drawMouseDown = True
    End Sub

    Private Sub PictureBox1_MouseUp(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseUp
        drawMouseDown = False
    End Sub

    Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseMove
        Dim g As Graphics = Graphics.FromImage(drawCanvas)
        Static coord As New Point
        If drawMouseDown Then
            g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
            drawMyBrush.StartCap = Drawing2D.LineCap.Round
            drawMyBrush.EndCap = Drawing2D.LineCap.Round
            g.DrawLine(drawMyBrush, coord.X, coord.Y, e.X, e.Y)
            g.Dispose()
            PictureBox1.Image = drawCanvas
            Me.Refresh()
        End If
        coord = e.Location
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        PictureBox2.Image = PictureBox1.Image 'Why does this not just update the PicBox2 image once?!? (or only when the Button is clicked)
    End Sub

End Class

期望

当我继续在 PictureBox1 上绘制时,单击 Button1 时,我希望 PictureBox2 包含 PictureBox1 图像。 >我确实希望它会在用户画图时继续更新 PictureBox2

2 个答案:

答案 0 :(得分:1)

您怀疑,PictureBox2.Image = PictureBox1.Image将前者称为后者。

您可以做的是clone图片:

PictureBox2.Image = DirectCast(PictureBox1.Image.Clone(), Image)

答案 1 :(得分:0)

因为您要将PictureBox2的Image属性引用到PictureBox1.Image。因此,当它们都指向同一个参考时,对PictureBox的image属性之一的任何更改都会影响另一个。

为了避免这种情况,请基于PictureBox1.Image创建一个Bitmap对象的新实例,并将其设置为PictureBox2.Image:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    PictureBox2.Image = New Bitmap(PictureBox1.Image)
End Sub