有没有办法画出带有多个彩色水平区域的文本?作为示例,我想绘制文本"Hello“,下半部分为红色,上半部分为绿色。要使用的文本必须是动态的。对于普通的纹理,我只需要使用Draw方法并传递一个子矩形来绘制不同颜色的纹理部分,但是对于文本呢?
发布于 2011-09-03 04:58:23
最好的方法可能涉及自定义着色器。但是,你也应该能够用剪裁矩形来做到这一点。
为了清楚起见,您的文本应该在两次绘制在相同的位置。
发布于 2011-09-16 23:52:46
我会按照“糟糕的编码者”的建议做一个自定义效果,它需要一些数据发送到效果,下面的代码是你需要的HLSL,你需要在Color1和Color2之间逐个像素淡出字符串的颜色。您可以通过从其中减去.5并将用于lerp的值乘以10来使其变为纯色变化。
float4x4 Projection;
float4 Color1, Color2;
float FontHeight;
float2 Location;
Texture2D FontTexture;
sampler TextureSampler = sampler_state { texture = <FontTexture> ; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = clamp; AddressV = clamp;};
struct VertexShaderInput
{
float4 Position : POSITION0;
float2 Texture : TEXCOORD0;
};
struct VertexShaderOutput
{
float4 Position : POSITION0;
float2 Texture : TEXCOORD0;
float2 OriginalPosition : TEXCOORD1;
};
VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
VertexShaderOutput output;
output.OriginalPosition = input.Position;
output.Texture = input.Texture;
output.Position = mul(input.Position, Projection);
return output;
}
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
float4 fontColor = lerp (Color1, Color2, (1.0 / FontHeight) * (input.OriginalPosition.y - Location.y));
return tex2D(TextureSampler, input.Texture)* fontColor;
}
technique Technique1
{
pass Pass1
{
VertexShader = compile vs_2_0 VertexShaderFunction();
PixelShader = compile ps_2_0 PixelShaderFunction();
}
}以及使用它的C#。(显然你不需要设置每一帧效果的所有参数,我只是不想发布太多的方法,如果你需要完整的示例,我很乐意通过电子邮件发送给你)
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
fontEffect.Parameters["Projection"].SetValue(Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1));
fontEffect.Parameters["Color1"].SetValue(Color.Red.ToVector4());
fontEffect.Parameters["Color2"].SetValue(Color.Blue.ToVector4());
fontEffect.Parameters["FontHeight"].SetValue(font.LineSpacing);
FieldInfo fontTexture = typeof(SpriteFont).GetField("textureValue", BindingFlags.NonPublic | BindingFlags.Instance);
fontEffect.Parameters["FontTexture"].SetValue((Texture2D)fontTexture.GetValue(font));
fontEffect.CurrentTechnique.Passes[0].Apply();
spriteBatch.Begin( SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone, fontEffect);
spriteBatch.DrawString(font, "abcdefghijklmnopqrstuvxyz", new Vector2(10, 100), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}编辑:你可能会注意到,我不得不去掉精灵字体的纹理,这是一个非常烦人的私有字段!如果有人知道更好的方法,请告诉我!
发布于 2012-10-27 00:01:42
我知道这是一个古老的问题,但这个tool将允许您创建自定义位图字体与各种效果,如阴影,浮雕,发光。它将为您生成字体纹理,然后您可以编辑和添加多种颜色或其他后处理效果。在XNA中使用它只需添加到您的内容项目中,并将ContentProcessor设置为"Sprite Font Texture“。然后你可以像加载一个普通的精灵字体一样将它加载到你的游戏中。
https://stackoverflow.com/questions/7289089
复制相似问题