我目前正在使用圖形類創建遊戲中所有圖片的遊戲,我也試圖從單獨的線程中繪製圖片來阻止我的主線程凍結。但每次我嘗試運行程序時,窗體出現什麼也沒有它,我得到這個錯誤...從一個單獨的線程繪畫?
System.NullReferenceException:對象不設置到對象的實例。
在Single_Player.Form1.mainPaint(PaintEventArgs的E)在C:\用戶\塞繆爾\文件\視覺工作室2012 \項目\ Single_Player \ Single_Player \ Form1.vb的:行12
如果我的代碼做的工作,我期待它在屏幕上移動一個橢圓,反正這是我的代碼...
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim paintT As New Threading.Thread(AddressOf mainPaint)
paintT.Start()
End Sub
Private Sub mainPaint(e As PaintEventArgs)
e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
e.Graphics.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
Dim playerX As Integer = 0
Dim playerY As Integer = 206
Do While 0/0
e.Graphics.DrawRectangle(New Pen(Color.FromArgb(128, Color.Black)), 0, 0, 884, 24)
e.Graphics.FillRectangle(New SolidBrush(Color.FromArgb(128, Color.Black)), 0, 0, 884, 24)
e.Graphics.DrawString("Life: 5", New Font("DigifaceWide", 20, GraphicsUnit.Pixel), New SolidBrush(Color.FromArgb(191, Color.Green)), 2, 0)
e.Graphics.DrawString("Score: 0", New Font("DigifaceWide", 20, GraphicsUnit.Pixel), New SolidBrush(Color.FromArgb(191, Color.White)), 100, 0)
e.Graphics.FillEllipse(New SolidBrush(Color.FromArgb(128, Color.Blue)), playerX, playerY, 24, 24)
playerX = playerX + 1
playerY = playerY + 1
e.Graphics.Clear(Color.Transparent)
Threading.Thread.Sleep(50)
Loop
End Sub
更新(再次) 我到目前爲止的代碼(這時候我已經通過設計窗口中增加了一個定時器)...
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
Timer1.Interval = 50
Timer1.Start()
End Sub
Private Sub mainBackgroundPB_Paint(sender As Object, e As PaintEventArgs) Handles Timer1.Tick
e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
e.Graphics.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
e.Graphics.DrawRectangle(New Pen(Color.FromArgb(128, Color.Black)), 0, 0, 884, 24)
e.Graphics.FillRectangle(New SolidBrush(Color.FromArgb(128, Color.Black)), 0, 0, 884, 24)
e.Graphics.DrawString("Life: 5", New Font("DigifaceWide", 20, GraphicsUnit.Pixel), New SolidBrush(Color.FromArgb(191, Color.Green)), 2, 0)
e.Graphics.DrawString("Score: 0", New Font("DigifaceWide", 20, GraphicsUnit.Pixel), New SolidBrush(Color.FromArgb(191, Color.White)), 100, 0)
e.Graphics.FillEllipse(New SolidBrush(Color.FromArgb(128, Color.Blue)), playerX, playerY, 24, 24)
playerX = playerX + 1
playerY = playerY + 1
e.Graphics.Clear(Color.Transparent)
End Sub
這是因爲'PaintEventArgs'爲空,你有沒有從程序線程 – vmeln 2013-04-10 13:50:53
也是爲什麼你要畫上一個differeent線程傳遞給'mainPaint',如果你想要的東西發生只使用一個計時器因爲你不能從另一個線程繪製。 – user1937198 2013-04-10 13:52:19
@VolodymyrMelnychuk:那麼我將如何將參數傳遞給mainPaint? – Sam 2013-04-10 13:58:00