The conversion to DirectX 8 Graphics from DirectDraw poses a few challenges, and one apparent stumbling block is the lack of direct support for color keys. The use of source color keying in DirectDraw was commonly used to draw sprites with transparent regions, by not drawing pixels of an application specified color when blitting a bitmap.
Rather than supporting color keys, DirectX 8 Graphics relies on the use of a separate alpha channel in the source image to specify the amount of opacity / transparency of each pixel. This provides a much finer level of control, allowing for translucent objects and finely feathered edges.
If the simple on/off control provided by color keys is what you need, though, this is easily simulated in DirectX 8 Graphics. This article will cover the basics required for simulating source color keys.
Loading the Image
To render with transparency, you will need to generate a texture which has an alpha layer, with pixels of the desired key color set to transparent. This can be performed automatically by the D3DXCreateTextureFromFileEx() function, by setting the ColorKey parameter to the desired key color. For example, the following loads a bitmap and sets all magenta pixels transparent:
Note that the alpha portion of the value specified for ColorKey must be 255, to denote an opaque color. This is because the image being loaded has no alpha, and thus all pixels are considered opaque. Failing to do this will cause no pixels to be set as transparent.
Rendering the Image
Simply having an alpha channel does not cause a texture to be rendered with transparency. Alpha blending must be enabled (it is off by default), and the proper blending factors must be applied. To do this, set the following render states prior to drawing with the texture:
This causes the texture to be multiplied by its alpha component, and the current surface being rendered to to be multiplied by the inverse of the textures alpha component. The results are then added to determine the resulting pixel color.
At this point you are ready to render the texture to the screen. If you need information on performing a simple 2D blit with the loaded texture, check out A Simple Blit Function for Direct3D.
After you are finished rendering textures containing transparency, restore the render states back to their defaults:
Visitors Since 1/1/2000: