OpenGL 上下文丢失后如何重新加载 libgdx 非托管纹理

2024-03-04

我正在通过网络下载图像,并使用以下命令将它们作为图像演员添加到我的 libgdx UI 中:

Pixmap pm = new Pixmap(data, 0, data.length);
Texture t = new Texture(pm);
TextureRegion tr = new TextureRegion(t,200,300);
TextureRegionDrawable trd = new TextureRegionDrawable(tr);
Image icon = new Image();
icon.setDrawable(trd);

鉴于此,我需要某种方法来重新加载纹理数据,因为当 OpenGL 上下文丢失时(例如,因为屏幕进入睡眠状态),纹理数据也会丢失。

我尝试制作自己的经理课程,添加

DynamicTextureManager.register(t, pm); // Register texture together with the source pixmap

到上面的代码片段,并在resume() I do:

DynamicTextureManager.reload();

经理类:

public class DynamicTextureManager {
    private static LinkedHashMap<Texture, Pixmap> theMap = new
      LinkedHashMap<Texture,Pixmap>();
    public static void reload() {
        Set<Entry<Texture,Pixmap>> es = theMap.entrySet();
        for(Entry<Texture,Pixmap> e : es) {
            Texture t = e.getKey();
            Pixmap p = e.getValue();

            t.draw(p, 0, 0);
        }   
    }

    public static void register(Texture t, Pixmap p) {
        theMap.put(t, p);
    }
}

但这并没有帮助 - 我最终仍然会卸载纹理并得到白色区域而不是图像。

这应该怎么做呢?我还没有找到任何代码来证明这一点!


添加我的解决方案作为参考。我现在向我的管理器注册 Image 对象和 Pixmap 对象,在 reload() 上,从 Pixmap 重新创建纹理,并为旧图像设置新纹理。对我有用,但欢迎更优雅的解决方案。

import java.util.Map.Entry;
public class DynamicTextureManager {
    private static final class MapData {
        Pixmap pixmap;
        int width;
        int height;
    }

    private static WeakHashMap<Image, MapData> theMap = new WeakHashMap<Image, MapData>();

    public static void reload() {
        Set<Entry<Image, MapData>> es = theMap.entrySet();
        for (Entry<Image, MapData> e : es) {
            Image i = e.getKey();
            MapData d = e.getValue();

            Texture t = new Texture(d.pixmap);
            TextureRegion tr;
            if(d.width == -1 || d.height == -1) {
                tr = new TextureRegion(t);
            }
            else {
                tr = new TextureRegion(t,d.width, d.height);                
            }
            TextureRegionDrawable trd = new TextureRegionDrawable(tr);
            i.setDrawable(trd);
        }
    }

    public static void register(Image i, Pixmap p) {
        MapData d = new MapData();
        d.pixmap = p;
        d.width = -1;
        d.height = -1;
        theMap.put(i, d);
    }

    public static void register(Image i, Pixmap p, int width, int height) {
        MapData d = new MapData();
        d.pixmap = p;
        d.width = width;
        d.height = height;

        theMap.put(i, d);
    }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

OpenGL 上下文丢失后如何重新加载 libgdx 非托管纹理 的相关文章

随机推荐