java - 将 GLSurfaceView 的屏幕捕获到位图

标签 java android screen-capture glsurfaceview

我需要能够在某个时刻捕捉到 GLSurfaceView 的图像。我有以下代码:

relative.setDrawingCacheEnabled(true);
screenshot = Bitmap.createBitmap(relative.getDrawingCache());
relative.setDrawingCacheEnabled(false);
Log.v(TAG, "Screenshot height: " + screenshot.getHeight());
image.setImageBitmap(screenshot); 

GLSurfaceView 包含在 RelativeLayout 中,但我也尝试直接使用 GLSurfaceView 来 try catch 图像。有了这个,我认为屏幕捕获了一个透明的图像,即那里什么都没有。任何帮助将不胜感激。

最佳答案

SurfaceViewGLSurfaceView 在它们的窗口中打洞以显示它们的表面。换句话说,它们具有透明区域。

因此,您无法通过调用 GLSurfaceView.getDrawingCache() 来捕获图像。

如果你想从 GLSurfaceView 获取图像,你应该在 GLSurfaceView.onDrawFrame() 中调用 gl.glReadPixels()

我修补了 createBitmapFromGLSurface 方法并在 onDrawFrame() 中调用它。

(原始代码可能来自 skuld 的代码。)

private Bitmap createBitmapFromGLSurface(int x, int y, int w, int h, GL10 gl)
        throws OutOfMemoryError {
    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) {
        return null;
    }

    return Bitmap.createBitmap(bitmapSource, w, h, Bitmap.Config.ARGB_8888);
}

关于java - 将 GLSurfaceView 的屏幕捕获到位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5514149/

相关文章:

java - IntentService onCreate() 已调用但 onHandleIntent() 未调用

java - 在 WebDriver 中使用稳健的 Try Catch 方法?

android - 分享 Intent 不适用于 Facebook Messenger

android - 使用 Kotlin 函数特性如何使这段代码更好?

windows - 如何使用ffmpeg一次记录两个窗口?

c# - 在 C# 中获取屏幕像素颜色的最快方法

java - 如何将这个 if-else 简化为一条语句?

java - 如何处理消息包中变量的存在(本地化)

java - 如何放大或缩小 JComponent?

c# - 在 C# 中捕获游戏屏幕截图的最快方法?(每秒超过 20 张图像)