This is my code:
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
There is an actual background image centered inside PictureBox1, which I added in the Designer. But when I debug, I get the error message:
InvalidOperationException was unhandled
What am I doing wrong?
That cannot work. PictureBox1 doesn’t yet have a value when this statement executes, that doesn’t happen until the InitializeComponent() method runs. You probably never heard about that yet, the magic incantation is you typing “Public Sub New”. When you press enter then you’ll see this:
That’s the constructor, a very important part of a .NET class. Note the “Add any initialization” comment that was generated. That’s where you initialize TheImage. To make it look like this:
If this is all still mysterious then hit the books to learn more.