2012-12-13 44 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