dir.by  
  Поиск  
Компьютер, программы
MonoGame - develop games on C# for computers (Windows, Linux), phones (Android, iOS), game consoles (Xbox, PlayStation, Nintendo Switch)
 Рисуем текст в новом MonoGame приложении 
посмотрели 10363 раз
обновлено: 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
Add a png file and draw a picture in the new MonoGame application
 
Next topic →
Books to learn MonoGame
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
MonoGame
What is MonoGame?
What is Mono (Virtual Machine for C# on 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
Create and run a MonoGame application on a computer (Windows) in Android emulator mode
Create a new MonoGame application on the computer (Windows) in emulator mode Android
Running and debugging the MonoGame app on your computer (Windows) in Android emulator mode
Runs the old version of the MonoGame app in debug in Android emulator mode
Running and debugging the MonoGame application on your phone via USB
Running the MonoGame application on an Android phone (creating an apk file)
Android (install)
Installing the Android Platform (SDK 7.1.1 API 25) in Visual Studio ...
Create a Android virtual device in Visual Studio
Installing, running the MonoGame application on a computer with the MacOSX system
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 Functionality
How to Draw a Rectangle in the New MonoGame App
Add a png file and draw a picture in the new MonoGame application
How to draw text in the new MonoGame app
Books
Books to learn MonoGame

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