using System; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace SpriteFontPlus.Samples.TextureAtlasFull { /// /// This is the main type for your game. /// public class Game1 : Game { private const int AtlasesPerRow = 3; private const int AtlasSize = 256; private const int TexturePadding = 16; GraphicsDeviceManager _graphics; SpriteBatch _spriteBatch; private DynamicSpriteFont _font; private Texture2D _white; private readonly Random _random = new Random(); public Game1() { _graphics = new GraphicsDeviceManager(this) { PreferredBackBufferWidth = 1024, PreferredBackBufferHeight = 768 }; Content.RootDirectory = "Content"; IsMouseVisible = true; Window.AllowUserResizing = true; } /// /// LoadContent will be called once per game and is the place to load /// all of your content. /// protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. _spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here _font = DynamicSpriteFont.FromTtf(File.ReadAllBytes(@"Fonts/DroidSans.ttf"), 20, AtlasSize, AtlasSize); _white = new Texture2D(GraphicsDevice, 1, 1); _white.SetData(new[] { Color.White }); GC.Collect(); } /// /// This is called when the game should draw itself. /// /// Provides a snapshot of timing values. protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here _spriteBatch.Begin(); var c = (char)_random.Next(32, 100); _font.Size = _random.Next(20, 40); _spriteBatch.DrawString(_font, c.ToString(), Vector2.Zero, Color.White); var count = 0; foreach (var texture in _font.Textures) { var x = (count % AtlasesPerRow) * (texture.Width + TexturePadding); var y = 50 + (count / AtlasesPerRow) * (texture.Height + TexturePadding); _spriteBatch.Draw(_white, new Rectangle(x, y, texture.Width, texture.Height), Color.Green); _spriteBatch.Draw(texture, new Vector2(x, y), Color.White); ++count; } _spriteBatch.End(); base.Draw(gameTime); } } }