Drawing Objects with Transparency

In certain types of applications, like games and multimedia programs, it's sometimes desirable to draw a background image and then draw some other images on top of it. If you just do this with a number of Image controls, you will get a gray box around your pictures where the transparent parts should be. You can get around this by using a DrawingArea. For example:

Suppose you have this background...

(photograph courtesy Philip Greenspun)

and you'd like to have our favorite shrimp guy chilling out in the water...

Try this code:

  DIM mypic AS Picture
  DIM bg AS Picture
  
  ' We've already created a DrawingArea called "dr" on the form.
  ' Load the background.
  bg = Picture["barcelona-aquarium.jpg"]
  
  ' Load the transparent picture.
  mypic = Picture["gambas7.png"]
  
  ' Turn on caching for the drawing area.
  ' 
  ' While it wasn't documented till recently, caching is really 
  ' helpful because it lets the drawing area handle its own 
  ' redrawing automatically.  Otherwise it gets erased whenever 
  ' something else obscures it, and in this case, since we're 
  ' drawing before the form gets shown, it never would be drawn 
  ' at all unless we cached it.
  '
  ' You can also set caching in the Properties dialog,
  ' but I wanted to explain it here.
  dr.cached = TRUE
  
  ' Go into drawing mode on our DrawingArea.
  Draw.begin(dr)
  
  ' Place the background in the upper left hand corner.
  ' (You'd want the drawing area to be the same size
  ' as your background.)
  Draw.picture(bg,0,0)
  
  ' Finally, draw our buddy the shrimp...
  Draw.picture(mypic,40,180)
  
  ' ...and leave drawing mode.
  Draw.end

Here's what should happen:

And here's the finished project.


Attachment: Action: Size: Date: Who: Comment:
barcelona-aquarium.jpg action 22326 16 Jan 2004 - 17:09 RobKudla  
gambas7.png action 9986 16 Jan 2004 - 17:09 RobKudla  
transparent-example.tar.gz action 66491 16 Jan 2004 - 17:11 RobKudla  
chilled-shrimp.png action 137049 16 Jan 2004 - 17:15 RobKudla