Android View转Bitmap(View截图)

Android  从view获取图片/bitmap

view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
//获取后copy -> bitmap 避免 RuntimeException Canvas: trying to use a recycled bitmap android.graphics.Bitmap@5bdf8f5
if (bitmap != null){ imageview.setImageBitmap(bitmap.copy(Bitmap.Config.ARGB_8888,true)); }
//清缓存,用于多次获取不同的图片 view.destroyDrawingCache();

 

 

从GLSurfaceView截图

public void screenshot(){
        int w = spWidth;
        int h = spHeight;
        int b[] = new int[(int) (w * h)];
        int bt[] = new int[(int) (w * h)];
        IntBuffer buffer = IntBuffer.wrap(b);
        buffer.position(0);
        GLES30.glReadPixels(0, 0, w, h, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, buffer);
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                int pix = b[i * w + j];
                int pb = (pix >> 16) & 0xff;
                int pr = (pix << 16) & 0x00ff0000;
                int pix1 = (pix & 0xff00ff00) | pr | pb;
                bt[(h - i - 1) * w + j] = pix1;
            }
        }
        Bitmap inBitmap = null;
        if (inBitmap == null || !inBitmap.isMutable()
                || inBitmap.getWidth() != w || inBitmap.getHeight() != h) {
            inBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
        }
        inBitmap.copyPixelsFromBuffer(buffer);
        inBitmap = Bitmap.createBitmap(bt, w, h, Bitmap.Config.RGB_565);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        inBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos);
    }

 从SurfaceView截图(视频流等黑屏情况)

 
Bitmap bitmap = Bitmap.createBitmap(surfaceView.getWidth(), surfaceView.getHeight(), Bitmap.Config.ARGB_8888); PixelCopy.request(this, bitmap, copyResult -> { if (copyResult ==PixelCopy.SUCCESS){ callBack.onResult(bitmap); } },new Handler());

 

 
posted @ 2022-08-11 16:16  西瓜皮不甜  阅读(771)  评论(0编辑  收藏  举报