这是我的密码:
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未被处理
我做错了什么?
发布于 2012-12-13 01:27:48
Public TheImage As Image = PictureBox1.BackgroundImage那是行不通的。当这个语句执行时,PictureBox1还没有一个值,这在InitializeComponent()方法运行之前不会发生。你可能还没听说过,神奇的咒语是你输入了"Public Sub“。当您按enter键时,您将看到以下内容:
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-13 01:27:59
代码的这一部分:
Public TheImage As Image = PictureBox1.BackgroundImage在调用TheImage之前初始化InitializeComponent,因此此时还没有创建PictureBox1。当我将这一段移动到Form_Load中时,一切都很完美:
Public TheImage As Image
'...
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
TheImage = PictureBox1.BackgroundImage
End Subhttps://stackoverflow.com/questions/13851337
复制相似问题