来自 glSurfaceView 的位图为空

bitmap from glSurfaceView is empty

public Bitmap getBitmapFromGlSurface(int x, int y, int w, int h){
    ByteBuffer buff = ByteBuffer.allocate(h * w * 4);
    Bitmap bitmap;

    try {
        GLES20.glReadPixels(x, y, w, h, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buff);
        bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        bitmap.copyPixelsFromBuffer(buff);
        Matrix matrix = new Matrix();
        matrix.postScale(1, -1, w / 2, h / 2); // We have to flip it upside down because opengl has inverted y axis
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);

    } catch (GLException e) {
        Log.d(TAG, "createBitmapFromGLSurface: " + e.getMessage(), e);
        return null;
    }
    return bitmap;
}

从 glSurfaceView 的 queueEvent 调用此方法

activity.glSurfaceView.queueEvent(new Runnable() {
        @Override
        public void run() {
            final Bitmap snapshotBitmap = activity.glSurfaceView.getRenderer().getBitmapFromGlSurface(0, 0, activity.glSurfaceView.getWidth(), activity.glSurfaceView.getHeight());

            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    bitmapReadyCallbacks.onBitmapReady(snapshotBitmap);
                }
            });
        }
    });

这里是glSurfaceView的初始化

    setZOrderOnTop(true);
    setEGLContextClientVersion(2);
    setEGLConfigChooser(8, 8, 8, 8, 0, 0);
    getHolder().setFormat(PixelFormat.TRANSLUCENT);
    renderer = new WriteGLRenderer(activity,this);
    setRenderer(renderer);
    setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    setPreserveEGLContextOnPause(true); 

因为你在 GLSurfaceView 初始化中使用了 setZOrderTop(true),它不会让你去它的视图并捕获它的像素。 为了获得位图,您必须从 JNI(C++) 端代码 return 字节数组 并将这些像素放入缓冲区。 这是方法

    public Bitmap getBitmapFromGlSurface(int w, int h){
            Bitmap bitmap;
            try {
                ByteBuffer buff = ByteBuffer.wrap(WriteViewActivity.getSnapshot());
                buff.rewind();
                bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
                bitmap.copyPixelsFromBuffer(buff);
                buff.clear();
                Matrix matrix = new Matrix();
                matrix.postScale(1, -1, bitmap.getWidth() / 2, bitmap.getHeight() / 2); // We have to flip it upside down because opengl has inverted y axis
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, (int)(bitmap.getWidth()), (int)(bitmap.getHeight() ), matrix, true);
            } catch (GLException e) {
                Log.e(TAG, "createBitmapFromGLSurface: " + e.getMessage(), e);
                return null;
            }
            return bitmap;
        }