Nov 032013

In previous article, we have seen a basic XNA application illustrating how to load a texture and how to move it around.

Lets see now how to write a text : load a spritefont as content, and use the drawstring method.

First lets look at a spritefont (in the zip file).
This is a simple XML file where you describe the font you want to use : font name, size, etc.

But you cannot use use as is in your XNA code.
You need to turn it into a XNA content (XNB file -> myfont.xnb next to exe file).
As my VS2013 does not manage XNA projects and contents, I use XNA Content Compiler.
Choose content type, select myfont.spritefont, input the destination folder and press compile !

Attached to this post the project files. xna_demo_2

Below the code for a quick review.

Imports Microsoft.Xna.Framework
Imports Microsoft.Xna.Framework.Graphics
Imports Microsoft.Xna.Framework.Audio
Imports Microsoft.Xna.Framework.Content
Imports Microsoft.Xna.Framework.Media
Imports Microsoft.Xna.Framework.Input

Public Class Game
Inherits Microsoft.Xna.Framework.Game
'Fields in our game graphic manager etc'
Dim graphics As GraphicsDeviceManager
Dim SpriteBatch As SpriteBatch
Dim font1 As SpriteFont
Public Sub New()
graphics = New GraphicsDeviceManager(Me)
End Sub

Protected Overrides Sub Initialize()
'TODO: Add your initialization logic here'
End Sub
Protected Overrides Sub LoadContent()
' TODO: use this.Content to load your game content here'
' Create a new SpriteBatch, which can be used to draw textures.'
SpriteBatch = New SpriteBatch(GraphicsDevice)
'lets create a font
font1 = Content.Load(Of SpriteFont)("myfont")
End Sub
Protected Overrides Sub UnloadContent()
'TODO: Unload any non ContentManager content here'
End Sub
Protected Overrides Sub Update(ByVal gameTime As Microsoft.Xna.Framework.GameTime)
'Allows the game to exit'
If GamePad.GetState(PlayerIndex.One).Buttons.Back = ButtonState.Pressed Then
End If
'TODO: Add your update logic here'
End Sub
Protected Overrides Sub Draw(ByVal gameTime As Microsoft.Xna.Framework.GameTime)
'TODO: Add your drawing code here'
'write text
SpriteBatch.DrawString(font1, "Ceci est un Test !!!", New Vector2(20.0F, 20.0F), Color.White)
End Sub
End Class


 Posted by at 18 h 12 min

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>



Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.