我不确定我是否使用了正确的SpriteBatch参数,或者我的着色器编码不正确,但是,为了简单起见,我试图制作一个设置着色器的着色器所有像素的alpha到128.但是,似乎只有2种可能的α'。如果我将值设置为0,则不会显示任何内容,而任何其他值都会将alpha设置为255.绝对没有介于两者之间,我无法指出错误。这是绘制调用的代码(我想,因为我只是想在所有内容上将alpha设置为128,我绘制的内容是无关紧要的)
m_GridFadeEffect.Parameters["FadeDistance"].SetValue(GridDrawRadius);
m_GridFadeEffect.Parameters["Center"].SetValue(Center);
m_GridFadeEffect.Parameters["LineColor"].SetValue(new Vector4(GridLinesColor.R, GridLinesColor.G, GridLinesColor.B, GridLinesColor.A));
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, m_GridFadeEffect);
// Draw here
spriteBatch.End();
这是着色器
uniform extern float FadeDistance;
uniform extern float2 Center;
uniform extern float4 LineColor;
float4 PixelShaderFunction(float2 inCoord: TEXCOORD0) : COLOR0
{
float4 Return = LineColor;
Return.a = 128; // I also tried Return.a = 0.5f;
return Return;
}
technique
{
pass P0
{
PixelShader = compile ps_2_0 PixelShaderFunction();
}
}
答案 0 :(得分:1)
我建议您使用内置功能来实现它:
spriteBatch.Draw(myTexture, myLocation, Color.White * 0.5f); //set 50% transparency
如果要使用像素着色器,则应为:
sampler textureSampler;
float4 ps_main( float2 tex2D : TEXCOORD0 ) : COLOR0 {
float color = tex2D( textureSampler, tex2D.xy ); //get color at xy coordinate
color.a = 0.5f; //set 50% transparency
return color; //output it
}
technique {
pass Pass1 {
PixelShader = compile ps_2_0 ps_main(); //XNA also supports ps_3_0
}
}
现在将纹理传递给像素着色器:
myEffect.Parameters["textureSampler"] = myTexture;
应用它然后绘制:
myEffect.CurrentTechnique.Passes[0].Apply(); //first and unique pass
//draw here
答案 1 :(得分:0)
将BlendState.AlphaBlend传递给spritebatch.Draw()并返回.a = 0.5。 Here是很好的HLSL教程。第10部分可以帮助您解决问题。
答案 2 :(得分:0)
首先,HLSL使用0到1之间的值作为颜色值。要转换范围为0-255的颜色值,只需执行:
valueBetweenZeroAndOne = desiredColor/255
所需颜色为颜色的0-255值。
最简单的方法是使用spritebatch提供的默认着色器并传入白色乘以系数0-1。
在着色器中执行此操作的正确方法是:
sampler s0;
// You want to set this outside the shader program
float alpha = 1;
float4 pixelShader( float2 coords : TEXCOORD0 ) : COLOR0 {
float color = tex2D( s0, coords );
return (color.rgba * alpha);
}