XNA – Transparent Effect

Posted: December 4, 2009 in C#, Game Programming, Programming, XNA
Tags: , ,


If all you want to do is a 50% alpha, you can create that via a Vector4 in the color. The alpha float will be between 0 and 1 (0% and 100%) and you’d just use this color in your spritebatch while drawing the particle.

float alpha = .50f; 
Color color = new Color( 
    255 * (byte)alpha);

To rendering with transparent effect, example,  vertex with transparent alpha value or a .png image with transparent area, just add code below before effect.Begin() called

effect.GraphicsDevice.RenderState.AlphaBlendEnable = true;
effect.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
effect.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;

In my example code, i will render some line, a transparent line. Befor rendering, i save some properties value of GraphicsDevice object, so i can restore it’s state after rendering

public void Draw(Matrix viewMatrix, Matrix projectionMatrix)
    bool alphaBlendEnable = basicEffect.GraphicsDevice.RenderState.AlphaBlendEnable;
    Blend sourceAlpha = basicEffect.GraphicsDevice.RenderState.SourceBlend;
    Blend inverseSourceAlpha = basicEffect.GraphicsDevice.RenderState.DestinationBlend;

    basicEffect.World = Matrix.Identity;
    basicEffect.View = viewMatrix;
    basicEffect.Projection = projectionMatrix;
    basicEffect.VertexColorEnabled = true;

    basicEffect.GraphicsDevice.RenderState.AlphaBlendEnable = true;
    basicEffect.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
    basicEffect.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;


    foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)

        device.VertexDeclaration = vertDeclaration;
        device.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, vertices, 0, vertices.Length / 2);


    basicEffect.GraphicsDevice.RenderState.AlphaBlendEnable = alphaBlendEnable;
    basicEffect.GraphicsDevice.RenderState.SourceBlend = sourceAlpha;
    basicEffect.GraphicsDevice.RenderState.DestinationBlend = inverseSourceAlpha;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s