如何为图像添加边框

时间:2012-12-13 01:00:27

标签: vb.net

这是我的代码:

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内有一个实际的背景图像,我在Designer中添加了它。但是当我调试时,我收到错误消息:

  

InvalidOperationException未处理

我做错了什么?

2 个答案:

答案 0 :(得分:1)

 Public TheImage As Image = PictureBox1.BackgroundImage

那不行。执行此语句时,PictureBox1还没有值,直到InitializeComponent()方法运行才会发生。你可能从未听说过,神奇的咒语是你输入“Public Sub New”。当您按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

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

答案 1 :(得分:1)

这部分代码:

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 Sub