Java Demo-- Transparency

You need a Java-enabled browser to view this applet.

This demo shows how easy it is to draw transparent images. For each frame, the buffer is cleared, and my living room is drawn. The three cats are then overlayed, one on top of another, transparently.

Overlaying a transparent image can be done by simply averaging each color component (red, green, blue). You can control the opacity of the transparent image by taking a weighted average, for example, weighting the transparent pixels by 0.1 and the current pixels by 0.9 results in a very gentle transparency.

Extracting a single color component is fairly difficult (one or two instructions each); each component has to be averaged (at least two instructions each) and re-assembling the components into an output pixel can also be slow (at least three instructions). But we can use a few tricks to speed this process up.

Unlike other demos, this buffer is not indexed color- it is 32 bits/pixel direct color (true color). Each color component (red, green, blue) consists of 8 bits, which represent a brightness, from 0 to 255. The components sit, in red-green-blue order, in each pixel. The leftover high 8 bits are used by Java, and should be set to all ones.

Using direct color means we can operate on all the color components at once, instead of one at a time. To average all the color components at once, we just add the 32-bit pixel values together and right shift by 1 place. To keep one component from overflowing into the next, we need to make sure there is a zero ahead of each color component-- we can do this by AND'ing all the input pixels by 0xfeFEfeFF (and we can do this beforehand!). No need to disassemble each component, no need to average each, and no need to re-assemble them afterwards. Instead of a dozen or more instructions per pixel, we use two.

Note that this is the same idea Intel's MMX instructions use, except they use 64-bit values and automatically handle overflow.

Link to the source code.


Back to Demo List.