0

我正在为 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() 将抛出一个已处理的异常。

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

4

1 回答 1

0

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

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

因此,解决方案是不用于ContentManager加载您的内容 - 至少不是默认实现。您可以从不缓存项目的类中继承您自己的类ContentManager,如下所示(代码基于此博客文章):

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事件,以便在图形设备“丢失”的情况下重新创建调整大小的纹理。

于 2013-02-06T15:16:48.900 回答