Display semi-transparent text
summary
Make the text appear semi-transparent.
Operating environment
Prerequisites
Supported XNA Versions |
|
Supported Platforms |
|
Windows Required Vertex Shader Version | 2.0 |
Windows Required Pixel Shader Version | 2.0 |
Operating environment
platform |
|
substance
By applying an opacity of 0.0~1.0 to the Color structure specified by the SpriteBatch.DrawString method, you can draw the text in semi-transparency. Most of the colors already defined in the properties of the Color structure are not set to opaque, so they can be made semi-transparent by applying opacity.
// 半透明の文字(75%)
this.spriteBatch.DrawString(this.font,
"Draw transparent text. (75%)",
new Vector2(50.0f, 100.0f), Color.White * 0.75f);
Color
constructor
Set the color. There is also a 0.0~1.0 float constructor.
r | byte | Specify the red color from 0~255. |
g | byte | Specify the green color as 0~255. |
b | byte | Specify the blue color from 0~255. |
a | byte | Specify the opacity (alpha component) from 0~255. |
By the way, the method of specifying the translucent color of sprites has changed since XNA Framework 4.0, and in order to specify a format like "new Color(255, 255, 255, 192)
" used in XNA Framewrok 3.1 and earlier, you need to specify the blend state of SpriteBatch with "BlendState.NonPremultiplied".
// スプライトの描画準備
this.spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied);
// 半透明の文字(75%)
this.spriteBatch.DrawString(this.font,
"Draw transparent text. (75%)",
new Vector2(50.0f, 100.0f), new Color(255, 255, 255, 192));
However, since the formula for calculating the output color has been changed, the edge of the character will be displayed in a darkened state.
About the output color
In the previous Tips, we used two blend patterns to display text as an example. On the other hand, beautiful translucent text was displayed as expected. On the other hand, the edges of the text were darkened. This is because the formula for outputting the color differs depending on the blend state used.
Set the parameters of the expression to
- result : Final output color
- source : The color of the texture you are trying to draw
- destination : The background color of the destination
- RGBA: Components of R (red), G (green), B (blue), and A (alpha (opacity)) respectively
And as defined, the calculation formula for the two blend states is as follows.
- BlendState.AlphaBlend (null default) (multiplied alpha)
- result = source.rgb + destination.rgb * (1 - source.a) // However, source.rgb is already alpha-applied
- BlendState.NonPremultiplied (Interpolated Alpha)
- result = source.rgb * source.a + destination.rgb * (1 - source.a)
In fact, if you find it with this formula, the value of result will be the same in both cases. However, if you use bilinear filtering, the above calculations are performed after color interpolation with adjacent pixels in the pixel shader, so the final output result will be different.
I would like to do some calculations for the sake of it. If the color of the text is white (Color.White), each color component of the pixel in which the text is displayed is (r:255, g:255, b:255, a:255). Pixels that do not display text are (r:0, g:0, b:0, a:0). If we make the text semi-transparent at 50% and interpolate it with the intermediate value of these two pixels (i.e., the edge of the character), how does the above two equations change the result?
By the way, the background color is (r:0, g:0, b:255, a:255). (Calculations are performed on white text and blue background)
Interpolation with BlendState.AlphaBlend (multiplied alpha)
Since alpha is applied to each element of the text color beforehand, the text color is halved by 255 (r:128, g:128, b:128, a:128) (Color.White * 0.5f"). Pixels that do not have text displayed are left as they are (r:0, g:0, b:0, a:0).
Since the bilinear filter formula is performed before the blend state calculates the background color, the color of the edge of the text is (r:64, g:64, b:64, a:64), which is an intermediate value between (r:128, g:128, b:128, a:128) and (r:0, g:0, b:0, a:0).
Here the expression
- result = source.rgb + destination.rgb * (1 - source.a)
If you apply it to:
- result = (r:64, g:64, b:64) + (r:0, g:0, b:255) * (1 - 0.25) // 0.25 indicates that a:64 is 25% of a:255
and the final composite color with the background color is (r:64, g:64, b:255).
Interpolation with BlendState.NonPremultiplied (interpolated alpha)
The color of the text is white (r:255, g:255, b:255), and only the alpha is halved to make it semi-transparent, so the value of the pixel in which the character is displayed is (r:255, g:255, b:255, a:128) (new Color(255, 255, 255, 128)). Pixels that do not display text remain the same (r:0, g:0, b:0, a:0).
Since the bilinear filter formula is performed before the blend state calculates the background color, the color of the edge of the text is (r:128, g:128, b:128, b:128, a:64), which is an intermediate value between (r:0, g:0, b:0, a:0).
Here the expression
- result = source.rgb * source.a + destination.rgb * (1 - source.a)
If you apply it to:
- result = (r:128, g:128, b:128) * 0.25 + (r:0, g:0, b:255) * (1 - 0.25)
and the final composite color with the background color is (r:32, g:32, b:224).
consideration
Since the background color is (r:0, g:0, b:255), interpolation with BlendState.AlphaBlend (r:64, g:64, b:255) allows the transparent color of the text to be beautifully expressed without losing the pigment of the background color. However, in the case of interpolation with BlendState.NonPremultiplied (r:32, g:32, b:224), the blue component is darker than the background color, so the edges of the text appear to be darkened (of course).
Red, Green is darker than BlendState.AlphaBlend.)
This default multiplied alpha from the XNA Framework 4.0 is described in detail in the blog "Hinikeni XNA", so if you want to know more, please refer to the link below. Over there, it is described as an example of drawing a red element against a white background.
All Codes
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
#if WINDOWS_PHONE
using Microsoft.Xna.Framework.Input.Touch;
#endif
namespace TransparentText
{
<summary>
ゲームメインクラス
</summary>
public class GameMain : Microsoft.Xna.Framework.Game
{
<summary>
グラフィックデバイス管理クラス
</summary>
private GraphicsDeviceManager graphics = null;
<summary>
スプライトのバッチ化クラス
</summary>
private SpriteBatch spriteBatch = null;
<summary>
スプライトでテキストを描画するためのフォント
</summary>
private SpriteFont font = null;
<summary>
GameMain コンストラクタ
</summary>
public GameMain()
{
// グラフィックデバイス管理クラスの作成
this.graphics = new GraphicsDeviceManager(this);
// ゲームコンテンツのルートディレクトリを設定
this.Content.RootDirectory = "Content";
#if WINDOWS_PHONE
// Windows Phone のデフォルトのフレームレートは 30 FPS
this.TargetElapsedTime = TimeSpan.FromTicks(333333);
// バックバッファサイズの設定
this.graphics.PreferredBackBufferWidth = 480;
this.graphics.PreferredBackBufferHeight = 800;
// フルスクリーン表示
this.graphics.IsFullScreen = true;
#endif
}
<summary>
ゲームが始まる前の初期化処理を行うメソッド
グラフィック以外のデータの読み込み、コンポーネントの初期化を行う
</summary>
protected override void Initialize()
{
// TODO: ここに初期化ロジックを書いてください
// コンポーネントの初期化などを行います
base.Initialize();
}
<summary>
ゲームが始まるときに一回だけ呼ばれ
すべてのゲームコンテンツを読み込みます
</summary>
protected override void LoadContent()
{
// テクスチャーを描画するためのスプライトバッチクラスを作成します
this.spriteBatch = new SpriteBatch(this.GraphicsDevice);
// フォントをコンテンツパイプラインから読み込む
this.font = this.Content.Load<SpriteFont>("Font");
}
<summary>
ゲームが終了するときに一回だけ呼ばれ
すべてのゲームコンテンツをアンロードします
</summary>
protected override void UnloadContent()
{
// TODO: ContentManager で管理されていないコンテンツを
// ここでアンロードしてください
}
<summary>
描画以外のデータ更新等の処理を行うメソッド
主に入力処理、衝突判定などの物理計算、オーディオの再生など
</summary>
<param name="gameTime">このメソッドが呼ばれたときのゲーム時間</param>
protected override void Update(GameTime gameTime)
{
// Xbox 360 コントローラ、Windows Phone の BACK ボタンを押したときに
// ゲームを終了させます
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
{
this.Exit();
}
// TODO: ここに更新処理を記述してください
// 登録された GameComponent を更新する
base.Update(gameTime);
}
<summary>
描画処理を行うメソッド
</summary>
<param name="gameTime">このメソッドが呼ばれたときのゲーム時間</param>
protected override void Draw(GameTime gameTime)
{
// 画面を指定した色でクリアします
this.GraphicsDevice.Clear(Color.CornflowerBlue);
// スプライトの描画準備
this.spriteBatch.Begin();
// 通常の文字
this.spriteBatch.DrawString(this.font,
"Draw normal text.",
new Vector2(50.0f, 50.0f), Color.White);
// 半透明の文字(75%)
this.spriteBatch.DrawString(this.font,
"Draw transparent text. (75%)",
new Vector2(50.0f, 100.0f), Color.White * 0.75f);
// 半透明の文字(50%)
this.spriteBatch.DrawString(this.font,
"Draw transparent text. (50%)",
new Vector2(50.0f, 150.0f), Color.White * 0.5f);
// 半透明の文字(25%)
this.spriteBatch.DrawString(this.font,
"Draw transparent text. (25%)",
new Vector2(50.0f, 200.0f), Color.White * 0.25f);
// スプライトの一括描画
this.spriteBatch.End();
// 登録された DrawableGameComponent を描画する
base.Draw(gameTime);
}
}
}