如果您使用的是第三方库,则这是一个完整的解决方案,您只需“传入”布局中定义的GLSurfaceView。你不会在渲染器的onDrawFrame()上有一个句柄,这可能是一个问题......
为此,您需要将其排队以便GLSurfaceView处理。
private GLSurfaceView glSurfaceView; // findById() in onCreate
private Bitmap snapshotBitmap;
private interface BitmapReadyCallbacks {
void onBitmapReady(Bitmap bitmap);
}
/* Usage code
captureBitmap(new BitmapReadyCallbacks() {
@Override
public void onBitmapReady(Bitmap bitmap) {
someImageView.setImageBitmap(bitmap);
}
});
*/
// supporting methods
private void captureBitmap(final BitmapReadyCallbacks bitmapReadyCallbacks) {
glSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
EGL10 egl = (EGL10) EGLContext.getEGL();
GL10 gl = (GL10)egl.eglGetCurrentContext().getGL();
snapshotBitmap = createBitmapFromGLSurface(0, 0, glSurfaceView.getWidth(), glSurfaceView.getHeight(), gl);
runOnUiThread(new Runnable() {
@Override
public void run() {
bitmapReadyCallbacks.onBitmapReady(snapshotBitmap);
}
});
}
});
}
// from other answer in this question
private Bitmap createBitmapFromGLSurface(int x, int y, int w, int h, GL10 gl) {
int bitmapBuffer[] = new int[w * h];
int bitmapSource[] = new int[w * h];
IntBuffer intBuffer = IntBuffer.wrap(bitmapBuffer);
intBuffer.position(0);
try {
gl.glReadPixels(x, y, w, h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, intBuffer);
int offset1, offset2;
for (int i = 0; i < h; i++) {
offset1 = i * w;
offset2 = (h - i - 1) * w;
for (int j = 0; j < w; j++) {
int texturePixel = bitmapBuffer[offset1 + j];
int blue = (texturePixel >> 16) & 0xff;
int red = (texturePixel << 16) & 0x00ff0000;
int pixel = (texturePixel & 0xff00ff00) | red | blue;
bitmapSource[offset2 + j] = pixel;
}
}
} catch (GLException e) {
Log.e(TAG, "createBitmapFromGLSurface: " + e.getMessage(), e);
return null;
}
return Bitmap.createBitmap(bitmapSource, w, h, Config.ARGB_8888);
}