SpriteFontの基礎
About
ゲーム中に、メニューやスコアの文字を表示したい場合は良くあります。そういった場面で用いられるのがSpriteFontです。ここではXNAでSpriteFontを表示するための基本的な手順を解説します。
SpriteFontの用意
- 「ソリューションエクスプローラ」から「Contentプロジェクト」を右クリックします。
- 「新規項目の追加」を選択し、開かれたウィンドウから「SpriteFont」を選択して「追加」します。
SpriteFontの読み込み
用意したSpriteFontはコンテント(リソース)として扱われるので、プログラムで利用するには、まずそれを読み込む必要があります。リソースの読み込みは例によって「LoatContentメソッド」内で実装します。フィールドに「SpriteFontクラス」の「spriteFont変数」を用意したとすると、先に追加したSpriteFontを読み込む記述は次の様になります。
spriteBatch = new SpriteBatch(this.GraphicsDevice); spriteFont = Content.Load<SpriteFont>("SpriteFont1");
SpriteFontの描画
読み込んだSpriteFontを利用して文字列を描画するには「SpriteBatch.DrawStringメソッド」を利用します。このメソッドで一般的に利用されるこ引数は次の様になっています。
- SpriteFont:利用するSpriteFont
- String:描画する文字列(※英数字限定)
- Vector2:描画する画面上の位置
- Color:描画する文字列の色
spriteBatch.DrawString (spriteFont, "BasicsOfSpriteFont", new Vector2(10,10), Color.White);
なので例えば上のソースコードであれば、画面の左上から(10,10)の位置に、白いフォントで「BasicsOfSpriteFont」と描画されます。ここで注意したいのが、標準的なSpriteFontでは日本語の文字列が表示できないという点です。日本語表示についてはテクニックが必要になるのでここでは割愛します。
文字の大きさ・書体を変更する
描画する文字の色の変更については先の通り「SpriteBatch.DrawStringメソッド」で実行できましたが、SpriteFontで用いられる書体や文字の大きさは、基本的には予め変更しておく必要があります。「Contentプロジェクト」から追加した「SpriteFont」をダブルクリックすると、SpriteFontの編集へ移ることができます。SpriteFontを開いてみると分かりますが、XMLデータ形式で管理されていることが分かります。
<!-- Modify this string to change the font that will be imported. --> <FontName>Segoe UI Mono</FontName> <!-- Size is a float value, measured in points. Modify this value to change the size of the font. --> <Size>14</Size> <!-- Spacing is a float value, measured in pixels. Modify this value to change the amount of spacing in between characters. --> <Spacing>0</Spacing> <!-- UseKerning controls the layout of the font. If this value is true, kerning information will be used when placing characters. --> <UseKerning>true</UseKerning> <!-- Style controls the style of the font. Valid entries are "Regular", "Bold", "Italic", and "Bold, Italic", and are case sensitive. --> <Style>Regular</Style>
XMLで定義された各種パラメータを変更することによって文字のサイズなどを変更することができます。主な設定項目は次の様になっています。
- FontName:フォント名(変更しないことを推奨します)
- Size:フォントサイズ
- Spacing:文字と文字の間の距離
- UseKerning:カーニング、文字間隔などの調整を有効化するか
- Style:Regular(普通)、Bold(太字)、Italic(斜体)、Bold, Italic(太字で斜体)から書体を選択する。