Home > database >  Adding Text to Image Drawn with GDI
Adding Text to Image Drawn with GDI

Time:12-14

I am displaying images using a timer and picturebox. The images seem to be adding on top of each other instead of displaying one, then removing that one, and loading another.

As the images are displayed, I would like to overlay text on the images.

Here is the code I am using to create images and text

 Dim fname As String = (Actually an array in images(jpg) that display with timer)
    Dim bm As New Bitmap(fname)
    PicBox.Image = bm
    findex -= 1  (index of image array)
    Dim g As Graphics = PicBox.CreateGraphics
    g.DrawImage(bm, 300, 10)
    g.DrawString("Kishman Tukus", New Font("Arial", 24, FontStyle.Bold), Brushes.Green, 400, 100)
    g.ResetTransform() '   
    g.Dispose()

I need the images to display in the picturebox one at a time using the timer and I need to overlay text on the images too.

can someone help me stop the images from adding to the picturebox instead of displaying one at a time? Or even better, don't use a PictureBox at all, just display images with text overlay? In any case, i need to stop the memory bleed. thank you

CodePudding user response:

I would expect to see something more like:

Dim bm As New Bitmap(fname)
Using g As Graphics = Graphics.FromImage(bm)
    g.DrawString("Kishman Tukus", New Font("Arial", 24, FontStyle.Bold), Brushes.Green, 400, 100)
End Using
PicBox.Image = bm

CodePudding user response:

I think it's important how you load the images. Do you really load each image by filename each time you show it? That's misleading, as you mentioned there is an array. The distinction is you keep references to these images and you are modifying each one. Remember this is a reference type so the original items gets modified. So you end up with text repeatedly being written over itself. The irony is that if you did actually load the image each tick, then you wouldn't actually have this problem :)

I made something along the lines of what you have (I think), where we use Object.Clone to make a copy in memory of each bitmap which you can modify without modifying the original image.

Private images As New List(Of Bitmap)()
Dim findex As Integer = 0

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Dim bmCopy = DirectCast(images(findex).Clone(), Bitmap)

    Using g As Graphics = Graphics.FromImage(bmCopy)
        g.DrawString(Guid.NewGuid().ToString(), New Font("Arial", 24, FontStyle.Bold), Brushes.Green, 400, 100)
    End Using

    PicBox.Image = bmCopy

    findex = (findex   1) Mod images.Count()
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    images.Add(My.Resources.Image1)
    images.Add(My.Resources.Image2)
    Timer1.Interval = 1000
    Timer1.Enabled = True
End Sub

There is no memory leak. You can check the memory increase but the GC eventually clears it out.

  • Related