我正在尝试使用spritebatch在XNA中绘制一个矩形图形。我有以下代码:
Texture2D rect = new Texture2D(graphics.GraphicsDevice, 80, 30);
Vector2 coor = new Vector2(10, 20);
spriteBatch.Draw(rect, coor, Color.Chocolate);
但是由于某些原因它没有绘制任何东西。有什么想法是错的吗?谢谢!
我正在尝试使用spritebatch在XNA中绘制一个矩形图形。我有以下代码:
Texture2D rect = new Texture2D(graphics.GraphicsDevice, 80, 30);
Vector2 coor = new Vector2(10, 20);
spriteBatch.Draw(rect, coor, Color.Chocolate);
但是由于某些原因它没有绘制任何东西。有什么想法是错的吗?谢谢!
以下是可以放入从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();
}
您的纹理没有任何数据。您需要设置像素数据:
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);
我刚刚做了一些非常简单的东西,你可以从你的 Draw 方法中调用它。 你可以轻松创建任意尺寸的矩形:
<code>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);
}
</code>
用法:
DrawRectangle(new Rectangle((int)playerPos.X, (int)playerPos.Y, 5, 5), Color.Fuchsia);