我正在开发游戏。我想在发生某些事情时突出显示屏幕上的一个点。
我创建了一个类来为我做这件事,并找到了一些代码来绘制矩形:
static private Texture2D CreateRectangle(int width, int height, Color colori)
{
Texture2D rectangleTexture = new Texture2D(game.GraphicsDevice, width, height, 1, TextureUsage.None,
SurfaceFormat.Color);// create the rectangle texture, ,but it will have no color! lets fix that
Color[] color = new Color[width * height];//set the color to the amount of pixels in the textures
for (int i = 0; i < color.Length; i++)//loop through all the colors setting them to whatever values we want
{
color[i] = colori;
}
rectangleTexture.SetData(color);//set the color data on the texture
return rectangleTexture;//return the texture
}
问题在于上面的代码在每次更新时都会被调用(每秒 60 次),而且编写时并未考虑优化。它需要非常快(上面的代码卡住了游戏,现在只有骨架代码)。
有什么建议吗?
注意:任何新代码都会很棒(线框/填充都可以)。我希望能够指定颜色。
最佳答案
SafeArea demo XNA Creators Club 网站上有专门执行此操作的代码。
您不必每帧都创建纹理,只需在 LoadContent
中创建。该演示中代码的精简版本:
public class RectangleOverlay : DrawableGameComponent
{
SpriteBatch spriteBatch;
Texture2D dummyTexture;
Rectangle dummyRectangle;
Color Colori;
public RectangleOverlay(Rectangle rect, Color colori, Game game)
: base(game)
{
// Choose a high number, so we will draw on top of other components.
DrawOrder = 1000;
dummyRectangle = rect;
Colori = colori;
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
dummyTexture = new Texture2D(GraphicsDevice, 1, 1);
dummyTexture.SetData(new Color[] { Color.White });
}
public override void Draw(GameTime gameTime)
{
spriteBatch.Begin();
spriteBatch.Draw(dummyTexture, dummyRectangle, Colori);
spriteBatch.End();
}
}
关于c# - 使用 XNA 绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2792694/