Рисовать прямоугольник в XNA с помощью SpriteBatch
Я пытаюсь нарисовать прямоугольную форму в XNA, используя spritebatch. У меня есть следующий код:
Texture2D rect = new Texture2D(graphics.GraphicsDevice, 80, 30);
Vector2 coor = new Vector2(10, 20);
spriteBatch.Draw(rect, coor, Color.Chocolate);
Но по какой-то причине он ничего не рисует. Любая идея, что неправильно? Спасибо!
Ответы
Ответ 1
У вашей текстуры нет данных. Вам нужно установить данные пикселя:
Texture2D rect = new Texture2D(graphics.GraphicsDevice, 80, 30);
Color[] data = new Color[80*30];
for(int i=0; i < data.Length; ++i) data[i] = Color.Chocolate;
rect.SetData(data);
Vector2 coor = new Vector2(10, 20);
spriteBatch.Draw(rect, coor, Color.White);
Ответ 2
Вот код, который вы можете поместить в класс, полученный из Game
. Это демонстрирует, где и как создать белую текстуру в 1 пиксель (плюс, как избавиться от нее, когда вы закончите). И как вы можете масштабировать и оттенять эту текстуру во время рисования.
Для рисования прямоугольников с плоским цветом этот метод предпочтительнее для создания самой текстуры с требуемым размером.
SpriteBatch spriteBatch;
Texture2D whiteRectangle;
protected override void LoadContent()
{
base.LoadContent();
spriteBatch = new SpriteBatch(GraphicsDevice);
// Create a 1px square rectangle texture that will be scaled to the
// desired size and tinted the desired color at draw time
whiteRectangle = new Texture2D(GraphicsDevice, 1, 1);
whiteRectangle.SetData(new[] { Color.White });
}
protected override void UnloadContent()
{
base.UnloadContent();
spriteBatch.Dispose();
// If you are creating your texture (instead of loading it with
// Content.Load) then you must Dispose of it
whiteRectangle.Dispose();
}
protected override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
GraphicsDevice.Clear(Color.White);
spriteBatch.Begin();
// Option One (if you have integer size and coordinates)
spriteBatch.Draw(whiteRectangle, new Rectangle(10, 20, 80, 30),
Color.Chocolate);
// Option Two (if you have floating-point coordinates)
spriteBatch.Draw(whiteRectangle, new Vector2(10f, 20f), null,
Color.Chocolate, 0f, Vector2.Zero, new Vector2(80f, 30f),
SpriteEffects.None, 0f);
spriteBatch.End();
}
Ответ 3
Я только что сделал что-то очень простое, которое вы можете вызвать из своего метода Draw
. Вы можете легко создать прямоугольник любых размеров:
private static Texture2D rect;
private void DrawRectangle(Rectangle coords, Color color)
{
if(rect == null)
{
rect = new Texture2D(ScreenManager.GraphicsDevice, 1, 1);
rect.SetData(new[] { Color.White });
}
spriteBatch.Draw(rect, coords, color);
}
Использование:
DrawRectangle(new Rectangle((int)playerPos.X, (int)playerPos.Y, 5, 5), Color.Fuchsia);