dir.by  
  Search  
Programming, development, testing
MonoGame - develop games on C# for computers (Windows, Linux), phones (Android, iOS), game consoles (Xbox, PlayStation, Nintendo Switch)
Рисуем текст в новом MonoGame приложении
  Looked at 8347 times    
 Рисуем текст в новом MonoGame приложении 
last updated: 16 Augusta 2023
1) Добавляем текстовый ресурс в проект
Нажмите правой кнопкой мыши на Content.mgcb
Выберите Monogame Pipeline Tool
Нажмите правой кнопкой мыши на папке "Content"
Выбираем SpriteFont Description (.spritefont) и нажимаем OK
Нажмите закрыть окно и выбирите 'yes' сохранить
Теперь переходим в Visual Studio и добавим C# код
1) в класс Game1 добавим переменную:
SpriteFont textBlock;

2) загрузка из ресурса
protected override void LoadContent()
{
...
    textBlock = Content.Load("mytext1");
...
}

3) внутри функции рисуем текст:
protected override void Draw(GameTime gameTime)
{
...
    spriteBatch.Begin();
    Vector2 position = new Microsoft.Xna.Framework.Vector2(100, 50); // position
    Microsoft.Xna.Framework.Color color = new Microsoft.Xna.Framework.Color(255, 255, 0);// color yellow
    spriteBatch.DrawString(textBlock, "Hello!", position, color); // draw text
    spriteBatch.End();

...
}
Весь код
  C#  
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Game1
{
     /// <summary>
     /// This is the main type for your game.
     /// </summary>
     public class Game1 : Game
     {
          GraphicsDeviceManager graphics;
          SpriteBatch spriteBatch;

          // переменная для текстур
          SpriteFont textBlock;

          public Game1()
          {
               graphics = new GraphicsDeviceManager(this);
               Content.RootDirectory = "Content";

               graphics.IsFullScreen = true;
               graphics.PreferredBackBufferWidth = 800;
               graphics.PreferredBackBufferHeight = 480;
               graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;
          }

          /// <summary>
          /// Allows the game to perform any initialization it needs to before starting to run.
          /// This is where it can query for any required services and load any non-graphic
          /// related content. Calling base.Initialize will enumerate through any components
          /// and initialize them as well.
          /// </summary>
          protected override void Initialize()
          {
               // TODO: Add your initialization logic here

               base.Initialize();
          }

          /// <summary>
          /// LoadContent will be called once per game and is the place to load
          /// all of your content.
          /// </summary>
          protected override void LoadContent()
          {
               // Create a new SpriteBatch, which can be used to draw textures.
               spriteBatch = new SpriteBatch(GraphicsDevice);

               // открываем текстовый элемент
               textBlock = Content.Load<SpriteFont>("mytext1");
          }

          /// <summary>
          /// UnloadContent will be called once per game and is the place to unload
          /// game-specific content.
          /// </summary>
          protected override void UnloadContent()
          {
               // TODO: Unload any non ContentManager content here
          }

          /// <summary>
          /// Allows the game to run logic such as updating the world,
          /// checking for collisions, gathering input, and playing audio.
          /// </summary>
          /// <param name="gameTime">Provides a snapshot of timing values.</param>
          protected override void Update(GameTime gameTime)
          {
               if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                    Exit();

               // TODO: Add your update logic here

               base.Update(gameTime);
          }

          /// <summary>
          /// This is called when the game should draw itself.
          /// </summary>
          /// <param name="gameTime">Provides a snapshot of timing values.</param>
          protected override void Draw(GameTime gameTime)
          {
               GraphicsDevice.Clear(Color.CornflowerBlue);

               // рисуем текст
               spriteBatch.Begin();
               Vector2 position = new Microsoft.Xna.Framework.Vector2(100, 50); // position
               Microsoft.Xna.Framework.Color color = new Microsoft.Xna.Framework.Color(255, 255, 0);// color yellow
               spriteBatch.DrawString(textBlock, "Hello!", position, color); // draw text
               spriteBatch.End();

               base.Draw(gameTime);
          }
     }
}
Запуск приложения
1) Компилирем приложение: Menu → Build → Build Solution (F7)
нет ошибок
2) Запускаем приложение: Menu → Debug → Start Without Debugging (Ctrl + F5)
Работает!
 
← Previous topic
Добавляем файл png и рисуем картинку в новом MonoGame приложении
 
Next topic →
Книги для изучения MonoGame
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
MonoGame
What is MonoGame?
Что такое Mono (виртуальная машина для C# в Unix) ?
What are the advantages of Monogame?
How to write a game in MonoGame and compile to different platforms: Windows computer, macOS computer, Android phone, iOS apple phone, Nintendo Switch game console
Download and install MonoGame
Download and install Microsoft Visual Studio to write MonoGame games on a computer with the Windows system
Open Visual Studio (to write a game using MonoGame)
Installing MonoGame (download and install) for Windows inside Visual Studio
Создаем и запускаем MonoGame приложение на компьютере (Windows) в режиме эмулятора Android
Create a new MonoGame application on the computer (Windows) in emulator mode Android
Запуск и отладка MonoGame приложения на компьютере(Windows) в режиме эмулятора Android
Запускается старая версия MonoGame приложения в debug в режиме эмулятора Android
Запуск и отладка MonoGame приложения на телефоне через USB
Запуск MonoGame приложения на Android телефоне (создание apk файла)
Android (устанавливаем)
Инсталлирование платформы Android (SDK 7.1.1 API 25) в Visual Studio ...
Create a Android virtual device in Visual Studio
Установка, запуск MonoGame приложения на компьютере с системой MacOSX
Installing, running MonoGame application on a computer with the operating system iOS (MacOSX) using Xamarin Studio
Installing, running MonoGame application on a computer with the operating system iOS (MacOSX) using Visual Studio
Функциональность MonoGame
Рисуем прямоугольник в новом MonoGame приложении
Добавляем файл png и рисуем картинку в новом MonoGame приложении
Рисуем текст в новом MonoGame приложении
Книги
Книги для изучения MonoGame

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика