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