Search code examples
.netvb.netgraphicsgdi+system.drawing

VB.NET Drawing Multiple Images onto a PictureBox at Different Locations


I have an Image inside a PictureBox and I have several other images that I want to draw onto the PictureBox at different locations.

For example, I have several images I want to draw onto a picture inside a PictureBox like these two stars (both are individual pictures (PNG) with transparent backgrounds):

star

I would like to draw multiple of these different stars at separate locations, pictured by an example on the picture below. (The US map is the image already present inside the PictureBox.

imgUS

I'm trying to write a function that when supplied/given a Point variable of the PictureBox's x and y values and the location of the image (such as My.Resources.RedCity or My.Resources.BlueCity) would draw the multiple images onto a PictureBox.

So far, I've accomplished to draw ONE picture onto the picturebox, but I am not able to draw multiple onto a PictureBox at different locations at one time since the other image disappears when I invalidate the image.

I was thinking of writing a function something like this to add a Picture/Point to some list or something and having something under the PictureBox's paint event, but I'm not sure how it would work for this.

Is there any function that exists or can be written that can be written that would be able to draw multiple images onto a PictureBox at different locations at the same time?

Thanks..


Solution

  • I was thinking of writing a function something like this to add a Picture/Point to some list or something and having something under the PictureBox's paint event, but I'm not sure how it would work for this.

    That's exactly the correct approach. Simple example:

    Public Class Form1
    
        Private dataPoints As New List(Of Tuple(Of Point, Integer))
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            dataPoints.Add(Tuple.Create(New Point(nudX.Value, nudY.Value), If(cbBlue.Checked, 0, 1)))
            PictureBox1.Invalidate()
        End Sub
    
        Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
            Dim G As Graphics = e.Graphics
            For Each dataPoint In dataPoints
                Dim img As Image = If(dataPoint.Item2 = 0, My.Resources.BlueCity, My.Resources.RedCity)
                G.DrawImage(img, dataPoint.Item1)
            Next
        End Sub
    
    End Class