How to take screenshot of WHOLE activity page prog

2019-01-18 13:43发布

问题:

How can I take screenshot of whole activity on Android, even if content is not visible? Ex. take screenshot of full chat and then generate image file?

I want screenshot invisible area too.

Thanks

回答1:

One way is to extract the bitmap of the current screen and save it. Try this:

public void takeScreenshot(){
    Bitmap bitmap = getScreenBitmap(); // Get the bitmap
    saveTheBitmap(bitmap);               // Save it to the external storage device.
}

public Bitmap getScreenBitmap() {
   View v= findViewById(android.R.id.content).getRootView();
   v.setDrawingCacheEnabled(true); 
   v.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
   v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); 

   v.buildDrawingCache(true);
   Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
   v.setDrawingCacheEnabled(false); // clear drawing cache
   return b;
}

Android take screen shot programmatically



回答2:

This is one way to take "screenshot" of a view. I haven't tested it so tell if it works

//View v is the root view/parent of your layout, for example LinearLayout or RelativeLayout (layout where you have placed content of which you want to take screenshot)
private Bitmap getBitmapFromView(View v) {
    Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas (bitmap);
    v.draw(canvas);
    // Returns screenshot
    return bitmap;
}


回答3:

public class MainActivity extends Activity {

ImageView imageView = null;
ScrollView sv = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sv = (ScrollView) findViewById(R.id.ssscrollView);
    imageView = (ImageView) findViewById(R.id.imgView);
    Button myBtn = (Button) findViewById(R.id.btn);
    myBtn.setOnClickListener(new View.OnClickListener() {

        @SuppressWarnings("deprecation")
        @Override
        public void onClick(View v) {

            View v1 = sv.getRootView();
            v1.setDrawingCacheEnabled(true);
            Bitmap bm = getBitmapFromView(v1);
            @SuppressWarnings("deprecation")
            BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
            ImageView view2 = (ImageView) findViewById(R.id.imgView);
            view2.setBackgroundDrawable(bitmapDrawable);
        }
    });

}

private Bitmap getBitmapFromView(View v) {
    Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    v.draw(canvas);
    return bitmap;
}

}