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

2) внутри функции добавим загрузку картинки:
На заметку! При загрузке изображения ресурс называется по имени файла без расширения
protected override void LoadContent()
{
...
    grass = Content.Load("ogorod");
...
}

3) внутри функции рисуем картинку:
protected override void Draw(GameTime gameTime)
{
...
    spriteBatch.Begin();
    spriteBatch.Draw(grass, Vector2.Zero, Color.White);
    spriteBatch.End();

...
}
Весь код
  C#     Весь исходный код
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

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

          // переменная для текстур
          Texture2D grass;

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

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

          /// Allows the game to perform any initialization it needs to before starting
          protected override void Initialize()
          {
               // TODO: Add your initialization logic here

               base.Initialize();
          }

          /// 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);

               // открываем картинку из Content/MonoGame (ресурс называется по имени файла без расширения)
               grass = Content.Load<Texture2D>("ogorod");
          }

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

          /// Allows the game to run logic such as updating the world,
          /// checking for collisions, gathering input, and playing audio.
          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);
          }

          /// This is called when the game should draw itself.
          protected override void Draw(GameTime gameTime)
          {
               GraphicsDevice.Clear(Color.CornflowerBlue);

               // рисуем картинку
               spriteBatch.Begin();
               spriteBatch.Draw(grass, Vector2.Zero, Color.White);
               spriteBatch.End();

               base.Draw(gameTime);
          }
     }
}
Запуск приложения
1) Компилирем приложение: Menu → Build → Build Solution (Ctrl + Shift + B)
нет ошибок
2) Запускаем приложение: Menu → Debug → Start Without Debugging (Ctrl + F5)
Работает!
 
← Previous topic
Рисуем прямоугольник в новом 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  
Яндекс.Метрика