C# 使用SpriteBatch在XNA中绘制矩形

C# 使用SpriteBatch在XNA中绘制矩形,c#,xna,draw,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); 但出于某种原因,它什么也没画。知道怎么了吗?谢谢 您的纹理没有任何数据。您需要

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

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

但出于某种原因,它什么也没画。知道怎么了吗?谢谢

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

 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);
Texture2D rect=新的Texture2D(graphics.GraphicsDevice,80,30);
颜色[]数据=新颜色[80*30];
对于(inti=0;i
以下是可以放入从
游戏
派生的类中的代码。这演示了在何处以及如何创建白色、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();
}

我刚刚做了一件非常简单的事情,你可以通过
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);

您可以在这里找到另一个解决方案:它涉及到创建SpriteBatch的扩展版本。