如何创建带自定义EGLSurface的GLSurfaceView?解决返回类型不匹配问题
解决GLSurfaceView自定义EGLSurface的类型兼容问题
核心原理
android.opengl.EGLSurface 类实现了 javax.microedition.khronos.egl.EGLSurface 接口,且二者底层指向同一个EGL对象句柄,因此可以通过强制转换实现类型兼容。
实现步骤(使用EGL14创建Surface)
重写EGLWindowSurfaceFactory的方法时,先通过EGL14创建Surface,再强制转换为旧接口类型返回:
glSurfaceView.setEGLWindowSurfaceFactory(new EGLWindowSurfaceFactory() { @Override public javax.microedition.khronos.egl.EGLSurface createWindowSurface( javax.microedition.khronos.egl.EGL egl, javax.microedition.khronos.egl.EGLDisplay display, javax.microedition.khronos.egl.EGLConfig config, Object nativeWindow) { // 将旧API的EGLDisplay、EGLConfig转换为EGL14可用类型 android.opengl.EGLDisplay egl14Display = (android.opengl.EGLDisplay) (Object) display; android.opengl.EGLConfig egl14Config = (android.opengl.EGLConfig) (Object) config; // 用EGL14创建WindowSurface android.opengl.EGLSurface egl14Surface = EGL14.eglCreateWindowSurface( egl14Display, egl14Config, nativeWindow, null, 0); // 强制转换为旧接口类型返回 return (javax.microedition.khronos.egl.EGLSurface) (Object) egl14Surface; } @Override public void destroySurface(javax.microedition.khronos.egl.EGL egl, javax.microedition.khronos.egl.EGLDisplay display, javax.microedition.khronos.egl.EGLSurface surface) { // 同样转换类型后用EGL14销毁Surface android.opengl.EGLDisplay egl14Display = (android.opengl.EGLDisplay) (Object) display; android.opengl.EGLSurface egl14Surface = (android.opengl.EGLSurface) (Object) surface; EGL14.eglDestroySurface(egl14Display, egl14Surface); } });
替代方案(直接使用旧EGL API)
如果不需要EGL14的新特性,也可以直接用旧API创建Surface,避免类型转换:
glSurfaceView.setEGLWindowSurfaceFactory(new EGLWindowSurfaceFactory() { @Override public javax.microedition.khronos.egl.EGLSurface createWindowSurface( javax.microedition.khronos.egl.EGL egl, javax.microedition.khronos.egl.EGLDisplay display, javax.microedition.khronos.egl.EGLConfig config, Object nativeWindow) { return egl.createWindowSurface(display, config, nativeWindow, null); } @Override public void destroySurface(javax.microedition.khronos.egl.EGL egl, javax.microedition.khronos.egl.EGLDisplay display, javax.microedition.khronos.egl.EGLSurface surface) { egl.destroySurface(display, surface); } });
内容的提问来源于stack exchange,提问作者porente
相关产品推荐
相关产品推荐

