How Do I Do Alpha Transparency Properly In XNA 4.0?
- by Soshimo
Okay, I've read several articles, tutorials, and questions regarding this. Most point to the same technique which doesn't solve my problem. I need the ability to create semi-transparent sprites (texture2D's really) and have them overlay another sprite.
I can achieve that somewhat with the code samples I've found but I'm not satisfied with the results and I know there is a way to do this. In mobile programming (BREW) we did it old school and actually checked each pixel for transparency before rendering.
In this case it seems to render the sprite below it blended with the alpha above it. This may be an artifact of how I'm rendering the texture but, as I said before, all examples point to this one technique. Before I go any further I'll go ahead and paste my example code.
public void Draw(SpriteBatch batch, Camera camera, float alpha)
{
int tileMapWidth = Width;
int tileMapHeight = Height;
batch.Begin(SpriteSortMode.Texture,
BlendState.AlphaBlend,
SamplerState.PointWrap,
DepthStencilState.Default,
RasterizerState.CullNone,
null, camera.TransformMatrix);
for (int x = 0; x < tileMapWidth; x++)
{
for (int y = 0; y < tileMapHeight; y++)
{
int tileIndex = _map[y, x];
if (tileIndex != -1)
{
Texture2D texture = _tileTextures[tileIndex];
batch.Draw(
texture,
new Rectangle(
(x * Engine.TileWidth),
(y * Engine.TileHeight),
Engine.TileWidth,
Engine.TileHeight),
new Color(new Vector4(1f, 1f, 1f, alpha )));
}
}
}
batch.End();
}
As you can see, in this code I'm using the overloaded SpriteBatch.Begin method which takes, among other things, a blend state. I'm almost positive that's my problem. I don't want to BLEND the sprites, I want them to be transparent when alpha is 0. In this example I can set alpha to 0 but it still renders both tiles, with the lower z ordered sprite showing through, discolored because of the blending. This is not a desired effect, I want the higher z-ordered sprite to fade out and not effect the color beneath it in such a manner.
I might be way off here as I'm fairly new to XNA development so feel free to steer me in the correct direction in the event I'm going down the wrong rabbit hole.
TIA