1

这是我的代码:

Public Class Form1
  Public TheImage As Image = PictureBox1.BackgroundImage
  Public Function AppendBorder(ByVal original As Image, ByVal borderWidth As Integer) As Image
    Dim borderColor As Color = Color.Red
    Dim mypen As New Pen(borderColor, borderWidth * 2)
    Dim newSize As Size = New Size(original.Width + borderWidth * 2, original.Height + borderWidth * 2)
    Dim img As Bitmap = New Bitmap(newSize.Width, newSize.Height)
    Dim g As Graphics = Graphics.FromImage(img)

    ' g.Clear(borderColor)
    g.DrawImage(original, New Point(borderWidth, borderWidth))
    g.DrawRectangle(mypen, 0, 0, newSize.Width, newSize.Height)
    g.Dispose()
    Return img
  End Function

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim OutputImage As Image = AppendBorder(TheImage, 2)
    PictureBox1.BackgroundImage = OutputImage
  End Sub
End Class

有一个以内部为中心的实际背景图像PictureBox1,我在设计器中添加了它。但是当我调试时,我收到错误消息:

InvalidOperationException 未处理

我究竟做错了什么?

4

2 回答 2

1
 Public TheImage As Image = PictureBox1.BackgroundImage

那是行不通的。执行此语句时 PictureBox1 还没有值,直到 InitializeComponent() 方法运行后才会发生。您可能从未听说过,神奇的咒语是您输入“Public Sub New”。当你按下回车键时,你会看到:

Public Sub New()

    ' This call is required by the Windows Form Designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

End Sub

这就是构造函数,是 .NET 类的一个非常重要的部分。请注意生成的“添加任何初始化”注释。这就是你初始化 TheImage 的地方。让它看起来像这样:

Public TheImage As Image

Public Sub New()
    InitializeComponent()
    TheImage = PictureBox1.BackgroundImage
End Sub

如果这一切仍然很神秘,那么请阅读书籍以了解更多信息。

于 2012-12-13T01:27:48.403 回答
1

这部分代码:

Public TheImage As Image = PictureBox1.BackgroundImage

在调用TheImage之前初始化,因此此时尚未创建。当我将这件作品移入 a时,一切正常:InitializeComponentPictureBox1Form_Load

Public TheImage As Image
'...
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
  TheImage = PictureBox1.BackgroundImage
End Sub
于 2012-12-13T01:27:59.253 回答