1. Computing

GDI+ Graphics in Visual Basic 2005 .NET

Drawing An Image on the Gradient

From , former About.com Guide

I also said I would include another image that changes with the temperature. Let's see how that works.

First, I should tell you that to get results that look substantially like my illustration above - a white pattern with a transparent background on the gradient - you will probably need a graphics editor. I started with an ordinary clip art file, converted it to a GIF file (for transparency - JPG doesn't support transparency), and removed a lot of shading bits in the image that look terrible in a transparent application. But for testing the GDI+ code here ... any small GIF, or even a JPG, that you have will work.

My program uses two images, one for "cold" and one for "hot". I create the Image objects i1 and i2 from files when they are declared. When the position of the middle point is less than .5, I move one into the displayed image i, otherwise I move the other one. Then I display that image using the Graphics object.

g.DrawImage( _
   i, StartRecX, StartRecY, i.Width, i.Height)

There's one final detail that will make our "temperature guage" a better program. If you have coded it up to this point, you will have seen a pretty bad "flicker" when the scroll bar "temperature" is changed. The problem is that redrawing takes some time.

VB.NET has an answer for this too!

In the trigonometric function graph from Part 2 of the tutorial, the lines were painted when the Refresh method was called for the PaintTrig Panel. Invalidate is another method that accomplishes about the same thing, but Invalidate offers some additional parameters that let you repaint just a region or a rectangle to minimize flicker. The code to repaint only the area with the graphic would be:

Me.Invalidate( _
   New Rectangle(StartRecX, StartRecY, i.Width, i.Height))

It's more common to change setting of the ControlStyles enumeration to eliminate flicker (and it usually works better too). The ControlStyles enumeration has a lot of members and some of them are designed specifically to make repainting your graphics smooth and flicker free.

The SetStyle method is used to change the ControlStyles enumeration like this:

SetStyle(ControlStyles.AllPaintingInWmPaint Or _
   ControlStyles.OptimizedDoubleBuffer Or _
   ControlStyles.UserPaint, True)

(Note: Framework 1.1 used DoubleBuffer. Although Framework 2.0 still accepts this, OptimizedDoubleBuffer is correct now.)

The complete source code is on the next page!

  1. About.com
  2. Computing
  3. Visual Basic
  4. Using VB.NET
  5. GDI+ Graphics in Visual Basic 2005 .NET

©2013 About.com. All rights reserved.