在XNA中顯示文字
定義字型檔案:
要顯示文字就必須要先定義字型檔(Sprite Font),在專案中的Content上按右鍵=>加入=>新增項目。
之後選擇建立Sprite Font並命名,在程式中只需要讀取該字型檔,就能夠用自己所設定的字形檔去產生文字,在運用XNA所提供的函數就可以將文字貼在想要顯示的地方。
該檔案就是設定想要輸出文字的字型、字體大小、文字間的距離等,這邊就來看字型檔中需要注意的幾行和他們的功用,定義完檔案之後必須要按存檔在專案中才能夠正確的讀取到該字型檔,或是對該字型檔有所變更的時候也必須先存檔,在程式方面才能夠正確的讀取修改內容的字型檔。










定義字型檔案範例:
















顯示文字程式流程:
接下來就是程式編輯的部份,首先必須要先宣告2個變數。


之後在LoadContent函數裡面撰寫讀取定義完的字型檔。

再來就可以到Draw函數裡面撰寫將要顯示的文字顯示出來,但還必須要先指定他要擺放的位置,還有想顯示的文字。


之後必須用到spriteBatch的成員函數DrawString,它和貼圖一樣必須放在成員函數Begin和End之間。



顯示文字程式範例:
01
using System;
02
using System.Collections.Generic;
03
using System.Linq;
04
using Microsoft.Xna.Framework;
05
using Microsoft.Xna.Framework.Audio;
06
using Microsoft.Xna.Framework.Content;
07
using Microsoft.Xna.Framework.GamerServices;
08
using Microsoft.Xna.Framework.Graphics;
09
using Microsoft.Xna.Framework.Input;
10
using Microsoft.Xna.Framework.Media;
11
using Microsoft.Xna.Framework.Net;
12
using Microsoft.Xna.Framework.Storage;
13
14
namespace test_text
15
{
16
public class Game1 : Microsoft.Xna.Framework.Game
17
{
18
GraphicsDeviceManager graphics;
19
SpriteBatch spriteBatch;
20
SpriteFont spriteFont; //存放字型的變數
21
Vector2 textpos; //存放文字的位置
22
23 public Game1()
24
{
25
graphics = new GraphicsDeviceManager(this);
26
Content.RootDirectory = "Content";
27
}
28
29 protected override void Initialize()
30
{
31
base.Initialize();
32
}
33
34 protected override void LoadContent()
35
{
36
spriteBatch = new SpriteBatch(GraphicsDevice);
37
spriteFont = Content.Load<SpriteFont>("SpriteFont1"); //讀取定義完的字型檔檔名
38
}
39
40 protected override void UnloadContent()
41
{
42
}
43
44 protected override void Update(GameTime gameTime)
45
{
46
base.Update(gameTime);
47
}
48
49 protected override void Draw(GameTime gameTime)
50
{
51
GraphicsDevice.Clear(Color.CornflowerBlue);
52
textpos = new Vector2(0, 0); //指定文字顯示的位置
53
string text = "TEXT"; //想要顯示的文字
54
spriteBatch.Begin();
55
spriteBatch.DrawString(spriteFont, text, textpos, Color.DarkBlue);
56
spriteBatch.End();
57
base.Draw(gameTime);
58
}
59
}
60
}
61

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23 public Game1()
24

25

26

27

28

29 protected override void Initialize()
30

31

32

33

34 protected override void LoadContent()
35

36

37

38

39

40 protected override void UnloadContent()
41

42

43

44 protected override void Update(GameTime gameTime)
45

46

47

48

49 protected override void Draw(GameTime gameTime)
50

51

52

53

54

55

56

57

58

59

60

61
顯示文字程式範例結果圖:
最後附上顯示文字的專案檔test-text.rar