2012-12-13 46 views
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异常是未处理

我在做什么错?

回答

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 

如果这仍然是神秘的,那么打这本书了解更多。

+0

你刚刚在这一张上挨了我11秒。 :) – Neolisk

+0

感谢汉斯。你是对的......即使我已经在VB编码了几年,但我并不知道这一点。谢谢(你的)信息! – NotQuiteThereYet

1

你的这部分代码:

Public TheImage As Image = PictureBox1.BackgroundImage 

初始化TheImageInitializeComponent之前被调用,因此没有在这一点上尚未创建PictureBox1。当我把这件作品搬到时,一切都很完美:

Public TheImage As Image 
'... 
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load 
    TheImage = PictureBox1.BackgroundImage 
End Sub 
+0

很高兴知道另一种方式来做到这一点。谢谢! – NotQuiteThereYet