【问题标题】:Draw Rectangle in XNA using SpriteBatch使用 SpriteBatch 在 XNA 中绘制矩形
【发布时间】:2011-08-10 17:44:01
【问题描述】:

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

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

但由于某种原因它没有绘制任何东西。知道有什么问题吗?谢谢!

【问题讨论】:

标签: c# xna draw


【解决方案1】:

这是您可以放入派生自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();
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案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);
      

      【讨论】:

        猜你喜欢
        • 2016-01-13
        • 2011-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多