【问题标题】:Load texture resized in XNA在 XNA 中加载调整大小的纹理
【发布时间】:2013-02-06 12:02:04
【问题描述】:

我正在为 Windows Phone XNA 进行开发,并希望在不需要完整图像的情况下加载较小尺寸的纹理以减少内存影响。

我目前的解决方案是使用渲染目标来绘制并将该渲染目标作为较小的纹理返回以供使用:

public static Texture2D LoadResized(string texturePath, float scale)
{
    Texture2D texLoaded = Content.Load<Texture2D>(texturePath);
    Vector2 resizedSize = new Vector2(texLoaded.Width * scale, texLoaded.Height * scale);
    Texture2D resized = ResizeTexture(texLoaded, resizedSize);
    //texLoaded.Dispose();
    return resized;
}

public static Texture2D ResizeTexture(Texture2D toResize, Vector2 targetSize)
{
    RenderTarget2D renderTarget = new RenderTarget2D(
        GraphicsDevice, (int)targetSize.X, (int)targetSize.Y);

    Rectangle destinationRectangle = new Rectangle(
        0, 0, (int)targetSize.X, (int)targetSize.Y);

    GraphicsDevice.SetRenderTarget(renderTarget);
    GraphicsDevice.Clear(Color.Transparent);

    SpriteBatch.Begin();
    SpriteBatch.Draw(toResize, destinationRectangle, Color.White);
    SpriteBatch.End();
    GraphicsDevice.SetRenderTarget(null);

    return renderTarget;
}

这在调整纹理大小时起作用,但从内存使用情况来看,纹理“texLoaded”似乎没有被释放。当使用未注释的 Dispose 方法时,SpriteBatch.End() 将抛出一个已处理的异常。

任何其他方式来加载调整大小以减少内存使用的纹理?

【问题讨论】:

    标签: windows-phone-7 memory xna texture2d rendertarget


    【解决方案1】:

    您的代码几乎没问题。它有一个小错误。

    您可能会注意到,它只会在您为任何给定纹理调用LoadResized 次引发异常。这是因为ContentManager 保留了它加载的内容的内部缓存——它“拥有”它加载的所有内容。这样,如果您加载两次,它只会将缓存的对象返回给您。通过调用Dispose,您将对象置于其缓存中!

    因此,解决方案是不使用 ContentManager 加载您的内容 - 至少不是默认实现。您可以从不缓存项目的ContentManager 继承您自己的类,就像这样(代码基于this blog post):

    class FreshLoadContentManager : ContentManager
    {
        public FreshLoadContentManager(IServiceProvider s) : base(s) { }
    
        public override T Load<T>(string assetName)
        {
            return ReadAsset<T>(assetName, (d) => { });
        }
    }
    

    传入Game.Services 创建一个。不要忘记设置RootDirectory 属性。

    然后使用这个派生的内容管理器来加载您的内容。您现在可以安全地(现在应该!)Dispose 您自己加载的所有内容。

    您可能还希望将事件处理程序附加到RenderTarget2D.ContentLost 事件,以便在图形设备“丢失”时重新创建调整大小的纹理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-31
      • 2012-12-01
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-01
      相关资源
      最近更新 更多