使用SpriteBatch在XNA中绘制矩形

时间:2011-04-22 02:29:55

标签: c# xna draw

我正在尝试使用spritebatch在XNA中绘制一个矩形形状。我有以下代码:

        Texture2D rect = new Texture2D(graphics.GraphicsDevice, 80, 30);
        Vector2 coor = new Vector2(10, 20);
        spriteBatch.Draw(rect, coor, Color.Chocolate);

但由于某种原因,它没有任何吸引力。知道什么是错的吗?谢谢!

3 个答案:

答案 0 :(得分:35)

以下是您可以放入从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();
}

答案 1 :(得分:19)

您的纹理没有任何数据。您需要设置像素数据:

 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 :(得分:8)

我刚刚制作了一些非常简单的内容,您可以使用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);