Take screenshot

为君一笑 提交于 2019-12-04 18:59:41

I actually just did this the other day and it was a pain to get a screenshot of the entire Activity, while also making sure to remove the StatusBar from the image (as it will appear as a black rectangle in the drawing cache). This method will also allow you to overlay the returned image with some color (ie. fading)):

public static Bitmap getActivitySnapshot(Activity activity, boolean fade){
    View view = activity.getWindow().getDecorView();
    view.setDrawingCacheEnabled(true);
    Bitmap bmap = view.getDrawingCache();

    Rect statusBar = new Rect();
    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(statusBar);
    Bitmap snapshot = Bitmap.createBitmap(bmap, 0, statusBar.top, bmap.getWidth(), bmap.getHeight() - statusBar.top, null, true);

    if(fade && snapshot != null){
        Canvas canvas = new Canvas(snapshot);
        Paint paint = new Paint();
        paint.setColor(Color.parseColor("#88121212"));
        canvas.drawRect(0, 0, snapshot.getWidth(), snapshot.getHeight(), paint);
    }

    view.setDrawingCacheEnabled(false);
    return snapshot;
}

If you don't want the fading part, the important parts would just be:

public static Bitmap getActivitySnapshot(Activity activity){
    View view = activity.getWindow().getDecorView();
    view.setDrawingCacheEnabled(true);
    Bitmap bmap = view.getDrawingCache();

    Rect statusBar = new Rect();
    activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(statusBar);
    Bitmap snapshot = Bitmap.createBitmap(bmap, 0, statusBar.top, bmap.getWidth(), bmap.getHeight() - statusBar.top, null, true);

    view.setDrawingCacheEnabled(false);
    return snapshot;
}

You may also want to catch the OutOfMemoryError that may be thrown when working with large Bitmaps.

This code can help you.

    /**
 * @param v view to capture it may be any Layout
 * @return
 */
 public static Bitmap captureScreen(View v)
 {
 Bitmap bitmap = null;

 try {
 if(v!=null)
 {
 int width = v.getWidth();
 int height = v.getHeight();

 Bitmap screenshot = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
 v.draw(new Canvas(screenshot));
 }
 } catch (Exception e)
 {
 Log.d("captureScreen", "Failed");
 }

 return bitmap;
 }

By screenshot, would a copy of your Root view help?

If so, you can use this:

public static Bitmap loadBitmapFromView(View view) {
    Bitmap bitmap = Bitmap.createBitmap(view.getLayoutParams().width, view.getLayoutParams().height, Bitmap.Config.ARGB_8888);                
    Canvas canvas = new Canvas(bitmap);
    view.layout(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
    view.draw(canvas);
    return bitmap;
}

Just pass your root view into this function and you can save the bitmap.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!