我想要做的是在XNA中使用alpha混合使绘制的纹理的一部分透明。例如,我将屏幕清除为某种颜色,让我们说蓝色。然后我绘制一个红色的纹理。最后,我绘制的纹理只是一个径向渐变,从中心的完全透明到边缘的完全黑色。我想要的是之前绘制的红色纹理在与径向渐变纹理相同的位置是透明的。所以你应该能够通过红色纹理看到蓝色背景。
我认为这样可行。
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin(SpriteBlendMode.None);
spriteBatch.Draw(bg, new Vector2(0, 0), Color.White);
spriteBatch.End();
spriteBatch.Begin(SpriteBlendMode.None);
GraphicsDevice.RenderState.AlphaBlendEnable = true;
GraphicsDevice.RenderState.AlphaSourceBlend = Blend.One;
GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.Zero;
GraphicsDevice.RenderState.SourceBlend = Blend.Zero;
GraphicsDevice.RenderState.DestinationBlend = Blend.One;
GraphicsDevice.RenderState.BlendFunction = BlendFunction.Add;
spriteBatch.Draw(circle, new Vector2(0, 0), Color.White);
spriteBatch.End();
GraphicsDevice.RenderState.AlphaBlendEnable = false;
但它似乎忽略了我的所有RenderState设置。我也尝试将SpriteBlendMode设置为AlphaBlend。它混合了纹理,但这不是我想要的效果。
任何帮助都将不胜感激。
答案 0 :(得分:6)
您要尝试的是Alpha通道屏蔽。最简单的方法是使用内容管道烘焙Alpha通道。但是如果由于某些原因你想在运行时这样做(大致)使用渲染目标(更好更快的解决方案就是编写着色器)
首先创建一个RenderTarget2D来存储和中间蒙版纹理
RenderTarget2D maskRenderTarget = GfxComponent.CreateRenderTarget(GraphicsDevice,
1, SurfaceFormat.Single);
设置renderTarget和设备状态
GraphicsDevice.SetRenderTarget(0, maskRenderTarget);
GraphicsDevice.RenderState.AlphaBlendEnable = true;
GraphicsDevice.RenderState.DestinationBlend = Blend.Zero;
GraphicsDevice.RenderState.SourceBlend = Blend.One;
设置要写入R,G,B通道的通道,并使用精灵批处理绘制第一个纹理
GraphicsDevice.RenderState.ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue;
spriteBatch.Draw(bg, new Vector2(0, 0), Color.White);
仅将通道设置为alpha,并绘制alpha蒙版
GraphicsDevice.RenderState.ColorWriteChannels = ColorWriteChannels.Alpha;
spriteBatch.Draw(circle, new Vector2(0, 0), Color.White);
现在可以将渲染目标恢复到后台缓冲区并使用Alpha混合绘制纹理。
maskedTexture = shadowRenderTarget.GetTexture();
...
另外不要忘记恢复状态:
GraphicsDevice.RenderState.ColorWriteChannels = ColorWriteChannels.All;
...