[英]Draw Rectangle in XNA using SpriteBatch
我試圖使用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
方法調用它。 您可以輕松創建任何尺寸的矩形:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.