Search code examples
vb.netgraphicsdrawingpicturebox

How to clear only drawing strings without redrawing the background image?


I was drawing everything (image and all strings) but when I draw the image, that loads my processor and blinks the image, two things that I don't want...

To fix this problem, I tried this:

  1. Set the main image as background image then draw over it, but when you try to "Clear(color.transparent)", it turns all black and you've to draw it again
  2. Add another PictureBox over main PictureBox but when you do this, the front image hide everything (as shown in picture 2)

Note: The background image is static and will never change, the only thing that'll change is the drawstring's...

Static background image

Drawstring's

Overlap problem


Solution

  • Please consider the following code snippet which might help you to solve the problem.

    Private ReadOnly backImage As Bitmap = 'The path of your background image.
    
    Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
        Dim srcRect As New Rectangle(0, 0, backImage.Width, backImage.Height)
        Dim desRect As Rectangle = PictureBox1.ClientRectangle
    
        Using bmp As New Bitmap(PictureBox1.Width, PictureBox1.Height)
            Using G As Graphics = Graphics.FromImage(bmp)
                G.SmoothingMode = SmoothingMode.HighQuality
                G.Clear(Color.Transparent)
                G.DrawImage(backImage, desRect, srcRect, GraphicsUnit.Pixel)
                G.DrawString("0.00", New Font("Arial", 12, FontStyle.Regular), Brushes.Red, desRect.Right - 80, 35)
                'and the other overlay painting ....
            End Using
    
            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic
            e.Graphics.DrawImageUnscaled(bmp, 0, 0)
        End Using
    End Sub
    

    I don't know how do you update your painting routine, nor whether the rest of your code has a possible effect on the painting. I think the mentioned code snippet is more than enough. Here is a quick demo that Invalidates (NOT Refresh) the painting every 100 milliseconds:

    SOQ58565613A

    Do you see any flickering? and here is the reading from my task manager while the demo is running:

    58565613B

    Almost nothing.

    I suggest that:

    • If you invalidate the painting through the TextChanged and/or ValueChanged events of the input controls, make sure that your controls are not in an infinite redundancies loop. Each event calls another event again and again. If not then:

    • Try your application in another machine just to make sure that your main one has no hardware issues. Maybe it's time for a new setup :).