0

I'm trying to code it so that i can create a picture box from a method in a class. However when my picture box is drawn it doesn't display any image, it only shows a white square of the specified dimensions in the specified location.

Here is the code which i am using to create said picture box:

 Public Sub DrawEnemy(ByRef formInstance)
        Dim enemypic As New PictureBox

        enemypic.Image = Image.FromFile("C:\fboi1\Enemy.Png")
        enemypic.Width = 64
        enemypic.Height = 64
        enemypic.Location = New Point(Me.EnemyPosX, EnemyPosY)
        enemypic.Visible = True
        formInstance.Controls.Add(enemypic)

    End Sub

And here is where i am calling the method from:

Dim Enemy1 As New computerControlled(1, 1)
        Enemy1.DrawEnemy(Me)
rioV8
  • 24,506
  • 3
  • 32
  • 49
fboi1
  • 3
  • 3
  • 1
    You probably mean `Public Sub DrawEnemy(ByVal formInstance as Form)` (or just `Public Sub DrawEnemy(formInstance as Form)`) – Jimi Sep 13 '20 at 23:50
  • 1
    Yep... definitely no reason to pass ByRef here, and you should definitely specify the type (and _turn on Option Strict for goodness sake!)_. Remember: **ByVal still passes references**... it's just the reference itself that has it's value copied. – Joel Coehoorn Sep 14 '20 at 00:44
  • Thanks for letting me know about the byval, i fixed it. Also, while the white box remains i noticed that when i drag the console window suddenly the white box turns into the image i wanted. Is this a problem with vb or still my code? – fboi1 Sep 14 '20 at 00:53
  • 1
    "when i drag the console window" What console window? What type of project did you start with? It should have been a WinForms project, which doesn't have a console window... – Idle_Mind Sep 14 '20 at 02:49
  • What size is your image? – Mary Sep 14 '20 at 04:38

2 Answers2

0

Please add the following code in your DrawEnemy() method:

enemypic.SizeMode = PictureBoxSizeMode.StretchImage
dear_vv
  • 2,350
  • 1
  • 4
  • 13
0

When i drag the console window suddenly the white box turns into the image i wanted.


Aha! This means the code is not causing the form to be repainted. We can trigger that by calling the Invalidate() function.

Public Sub DrawEnemy(formInstance As Form)
    Dim enemypic As New PictureBox

    enemypic.Image = Image.FromFile("C:\fboi1\Enemy.Png")
    enemypic.Width = 64
    enemypic.Height = 64
    enemypic.Location = New Point(Me.EnemyPosX, EnemyPosY)
    enemypic.Visible = True
    formInstance.Controls.Add(enemypic)

    formInstance.Invalidate()
End Sub

If you're calling this several times in a loop, you would instead handle this after the loop, where you also block repainting (to prevent flickering) until the loop is finished.

form.SuspendLayout()
For Each enemy In ...
    '...
    DrawEnemy(form)
Next
form.Invalidate()
form.ResumeLayout()

It's also possible you only need to Invalidate() the picturebox.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794