Image/Rectangle partial fade in xna
How do I partially fade a rectangle or an image in xna like so:
开发者_如何学编程I'm using xna 3.1 and SpriteBatch.Draw()
. I need it to be partially transparent so I can see what is behind it.
Just to add to Andrew's answer, there is a third (much slower) way to do this without writing a shader or a new batcher. Just use Texture2D's GetData method to extract the pixel data, go through it in a for loop changing the alpha values the way you want, and then use SetData to put it back. This is HORRIBLE way to do things if you are constantly changing the alpha value's, but it looks like you just want to change the alpha values once, so you'll just have additional overhead when loading the program and everything should work smoothly after that. Also, if you are only doing this to a small number of images, the performance difference is practically negligible. Here's some code to get you started:
Color[] texColors = new Color[myTexture.Width * myTexture.Height];
myTexture.GetData<Color>(texColors);
for(int i = 0; i < texColors.Length; i++)
{
//change alpha values the way you want
}
myTexture.SetData<Color>(texColors);
The "correct" way to do this would be to stop using SpriteBatch
and manually draw quads or write your own sprite batcher instead. This way you could individually control the vertex alpha values.
If you want a quick, somewhat hacky way to do it, add a custom pixel shader to your sprite batch. In this shader, take the texture-coordinates as input and use them to modulate the output alpha. Or alternately use a second texture to modulate the alpha values.
精彩评论