从PictureBox获取位图 - 对象的新实例

时间:2014-04-09 16:59:26

标签: vb.net winforms graphics picturebox

我有一个完美无缺的"用于将屏幕的一部分放入方形PictureBox的工作代码 我有一个完美无缺的"使用笔在图片框上绘图的工作代码 我完全不理解,为什么我不能在PictureBox中的位图上画笔 - 它只能在灰色背景上绘制。
解决方案(也按照谷歌)看似简单,但尝试从PictureBox.Image获取gg图形的任何方法都会导致("创建表单时出错。有关详细信息,请参阅Exception.InnerException。错误是:值不能为空。 参数名称:image"和"使用'新'用于创建对象的新实例的关键字...")。

我认为问题在于我将位图定义为sub之外的私有,但我无法弄清楚正确的概念......

Private bit As New System.Drawing.Bitmap(250, 250)
Private gg As Graphics = Graphics.FromImage(Me.PictureBox1.Image)
'            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
'            ^^^^^^^^^^ HERE IS THE PROBLEM ^^^^^^^^^^^^^^^^^^^^^^
'            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Private br As New Pen(Color.Red)
Private dwn As Boolean
Private lst As Point
Private firstrun As Boolean = True
Dim Tloustka As Integer = 10
Dim Barva As Integer

Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
    'gg = Graphics.FromImage(Me.PictureBox1.Image)
    dwn = True
End Sub


Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
    If dwn = True Then
        Dim s As Integer
        Dim xy As Point
        Dim br2 As New SolidBrush(Color.FromName("White"))
        s = Tloustka
        br.Color = Color.FromName("White")
        br.Width = Tloustka
        xy.X = e.X
        xy.Y = e.Y
        If firstrun = True Then
            lst = xy
            firstrun = False
        End If
        gg.FillEllipse(br2, xy.X - CLng(s / 2), xy.Y - CLng(s / 2), s, s)
        gg.DrawLine(br, lst, xy)
        lst = xy
        PictureBox1.Image = bit
    End If
End Sub

etc. etc. etc.

2 个答案:

答案 0 :(得分:1)

不要存储Graphic对象。只需在需要绘制内容时从位图创建它:

Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseMove
  If dwn = True Then
    Using g As Graphics = Graphics.FromImage(bit)
      Dim s As Integer
      Dim xy As Point
      Using br2 As New SolidBrush(Color.FromName("White"))
        s = Tloustka
        br.Color = Color.FromName("White")
        br.Width = Tloustka
        xy.X = e.X
        xy.Y = e.Y
        If firstrun = True Then
          lst = xy
          firstrun = False
        End If
        g.FillEllipse(br2, xy.X - CLng(s / 2), xy.Y - CLng(s / 2), s, s)
        g.DrawLine(br, lst, xy)
      End Using
    End Using
    lst = xy
    PictureBox1.Invalidate()
  End If
End Sub

然后使用PictureBox的paint事件来显示图像:

Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
  e.Graphics.DrawImage(bit, Point.Empty)
End Sub

确保丢弃图形对象。

答案 1 :(得分:0)

上述所有代码似乎有点过于复杂。就我而言,最简单的方法是按照以下步骤进行:

Dim bm As Bitmap   使用PictureBox1      bm =新位图(.Width,.Height)      PictureBox1.DrawToBitmap(bm,New Rectangle(0,0,.Width,.Height))   

结束

... /代码打印/

bm.Dispose

P.S。:任何控件都可以绘制到位图。