创建一个dll文件以将图像加载到表单但获取“System.NullReferenceException”

时间:2014-12-30 06:38:02

标签: vb.net dll

我创建了以下dll文件来加载图片并绘制图片

Imports System.Drawing

Namespace GDI
Public Class ImageManager
    Public Images As Dictionary(Of String, Image)

    Public Sub LoadImage(Name As String, Path As String)
        If Images.ContainsKey(Name) Then
            Exit Sub
        Else
            Try
                Dim i As Image = Image.FromFile(Path)
                Images.Add(Name, i)
            Catch ex As Exception

            End Try
        End If
    End Sub

    Public Sub RemoveImage(Name As String)
        If Images.ContainsKey(Name) Then Images.Remove(Name)
    End Sub

    Public Sub DrawImage(Surface As Object, Name As String, Position As Point, Optional Size As Point = Nothing)
        Try
            If Images.ContainsKey(Name) Then
                Dim G As Graphics = Surface.CreateGraphics

                If Size.IsEmpty Then
                    G.DrawImage(Images(Name), Position)
                Else
                    G.DrawImage(Images(Name), New Rectangle(Position.X, Position.Y, Size.X, Size.Y))
                End If
            End If
        Catch ex As Exception
        End Try
    End Sub
End Class

结束命名空间

我使用表单应用程序中的dll文件来加载图片。我把两张图片放在项目调试文件夹中。但是当我尝试运行该项目时。它给了我"" System.NullReferenceException"在

上的dll文件中
f Images.ContainsKey(Name) Then

以下是表单应用程序背后的代码:

Imports GFX.GDI

Public Class Form1
Private ImgMan As New ImageManager

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ImgMan.LoadImage("background", "Pic\background.jpg")
    ImgMan.LoadImage("download", "Pic\downlaod.jpg")
End Sub

Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
    ImgMan.DrawImage(Me, "runningman", New Point(0, 0), New Point(Me.Width, Me.Height))
End Sub
End Class

1 个答案:

答案 0 :(得分:0)

您尚未在上面的代码中初始化图像字典。编辑声明如下:

Public Images As new Dictionary(Of String, Image)