从xna中的纹理绘制矩形的不同方法之间的性能差异?

时间:2011-08-02 09:18:29

标签: c# xna texture2d drawrectangle

我正在尝试开发一个JRPG / dungeon爬行器作为夏季项目,我正在清理我的代码。在战斗中,它存在“健康栏”,一个健康栏由3个需要为每个角色绘制的矩形组成(总共2-8个字符,具体取决于上下文,一次最多可达24个健康栏)。

我绘制healbar的旧方法基于1个纹理,我从中获取了一个像素 并绘制一个矩形区域。基本上我使用“HealtBar”纹理作为颜色palet ...例如,如果源矩形是(0,0,1,1),它表示绘制一个黑色矩形。

Texture2D mHealthBar;
mHealthBar = theContentManager.Load<Texture2D>("HealthBar");

public override void Draw(SpriteBatch theSpriteBatch)
        {
            //draw healtbar
            theSpriteBatch.Draw(mHealthBar, new Rectangle((int)Position.X+5,
            (int)(Position.Y - 20), (MaxHealth * 5)+7, 15),
            new Rectangle(0, 0, 1, 1), Color.Black);

            theSpriteBatch.Draw(mHealthBar, new Rectangle((int)(Position.X + 8),
            (int)(Position.Y - 17), ((MaxHealth * 5)), (mHealthBar.Height) - 2),
            new Rectangle(2, 2, 1, 1), Color.White);

            theSpriteBatch.Draw(mHealthBar, new Rectangle((int)(Position.X + 8),
            (int)(Position.Y - 17), ((Health * 5)), (mHealthBar.Height) - 2),
            new Rectangle(3, 2, 1, 1), Color.Red);
      }

这不是一个好看的解决方案......所以我尝试创建一个抽象类,它可以减少代码量并增加代码的清晰度。

abstract class Drawer
{
    static private Texture2D _empty_texture;

    static public void DrawRect(SpriteBatch batch, Color color, Rectangle rect)
    {
        _empty_texture = new Texture2D(batch.GraphicsDevice, 1, 1);
        _empty_texture.SetData(new[] { Color.White });

        batch.Draw(_empty_texture, rect, color);
    }
}

使用新的Drawer类,我可以丢弃“mHealthBar”变量并以更漂亮的代码方式绘制矩形。但是当我开始使用新的方式绘制游戏时开始出现帧速率问题,旧的方式很顺利......帧率问题的原因是什么?

        Drawer.DrawRect(theSpriteBatch, Color.Black, new Rectangle((int)Position.X+5,
        (int)(Position.Y - 20), (MaxHealth * 5)+7, 15));

        Drawer.DrawRect(theSpriteBatch, Color.White, new Rectangle((int)(Position.X + 8),
        (int)(Position.Y - 17), (MaxHealth * 5), 9));

        Drawer.DrawRect(theSpriteBatch, Color.Red, new Rectangle((int)(Position.X + 8),
        (int)(Position.Y - 17), (Health * 5), 9));

1 个答案:

答案 0 :(得分:1)

问题在于,您每次要绘制时都要创建新纹理并设置颜色。

您应该做的只是创建一次纹理(加载其他内容时)。