Android GLSurfaceview 截屏

搜刮各个论坛组合一个直接可用的,可根据自己的的项目情况,修改封装

放在glsurfaceview的onDrawFrame方法中,外面添加一个boolean去控制执行,如果render是被动刷新,执行requestrender

public class FMScreenShotUtil {
    public static void screenShot(Context context,GL10 gl, int x, int y, int w, int h) {
        Bitmap bmp = createBitmapFromGLSurface(context,0, 0, w, h, gl);
        saveAndRefrash(context, bmp);
    }

    private static Bitmap createBitmapFromGLSurface(Context context,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);
    }


    private static String saveAndRefrash(Context context, Bitmap bitmap) {
        String cacheDirectory = Environment.getExternalStorageDirectory().getPath();
        long l = System.currentTimeMillis();
        String filePath = cacheDirectory + l + ".png";

        File imagePath = new File(filePath);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(imagePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (Exception e) {
        } finally {
            try {
                fos.close();
                bitmap.recycle();
                bitmap = null;

                //最后通知图库更新
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);//扫描单个文件
                intent.setData(Uri.fromFile(imagePath));//给图片的绝对路径
                context.sendBroadcast(intent);
            } catch (Exception e) {
            }
        }

        return filePath;
    }
}

你可能感兴趣的:(android基础)