18

I use below code to convert, but it seems can only get the content in the display screen and can not get the content not in the display screen.

Is there a way to get all the content even out of scroll?

Bitmap viewBitmap = Bitmap.createBitmap(mScrollView.getWidth(),mScrollView.getHeight(),Bitmap.Config.ARGB_8888);  
Canvas canvas = new Canvas(viewBitmap); 
mScrollView.draw(canvas);
Padma Kumar
  • 19,893
  • 17
  • 73
  • 130
Twos
  • 185
  • 1
  • 1
  • 7

5 Answers5

37

We can convert all the contents of a scrollView to a bitmap image using the code shown below

private void takeScreenShot() 
{
    View u = ((Activity) mContext).findViewById(R.id.scroll);

    HorizontalScrollView z = (HorizontalScrollView) ((Activity) mContext).findViewById(R.id.scroll);
    int totalHeight = z.getChildAt(0).getHeight();
    int totalWidth = z.getChildAt(0).getWidth();

    Bitmap b = getBitmapFromView(u,totalHeight,totalWidth);             

    //Save bitmap
    String extr = Environment.getExternalStorageDirectory()+"/Folder/";
    String fileName = "report.jpg";
    File myPath = new File(extr, fileName);
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(myPath);
        b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
        MediaStore.Images.Media.insertImage(mContext.getContentResolver(), b, "Screen", "screen");
    }catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {

    Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth,totalHeight , Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return returnedBitmap;
}
Abu Saad Papa
  • 1,908
  • 15
  • 20
  • 1
    this is the not working when use scrollTo views that wish to internally scroll their content http://developer.android.com/reference/android/view/View.html#scrollTo%28int,%20int%29 – LOG_TAG Oct 24 '14 at 10:55
  • This won't work on Android Oreo or higher. – Johann Jul 14 '21 at 12:21
  • 1
    The actual screenshotting code still works perfectly on Android 12, but indeed the file saving logic is now broken. – Luke Needham Feb 22 '22 at 13:37
9

The Pops answer is really good, but in some case you could have to create a really big bitmap which could trigger a OutOfMemoryException when you create the bitmap.

So I made a little optimization to be gently with the memory :)

public static Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {

   int height = Math.min(MAX_HEIGHT, totalHeight);
   float percent = height / (float)totalHeight;

   Bitmap canvasBitmap = Bitmap.createBitmap((int)(totalWidth*percent),(int)(totalHeight*percent), Bitmap.Config.ARGB_8888);
   Canvas canvas = new Canvas(canvasBitmap);

   Drawable bgDrawable = view.getBackground();
   if (bgDrawable != null)
      bgDrawable.draw(canvas);
   else
      canvas.drawColor(Color.WHITE);

   canvas.save();
   canvas.scale(percent, percent);
   view.draw(canvas);
   canvas.restore();

   return canvasBitmap;
}
paul gloaguen
  • 91
  • 1
  • 2
  • It creates a scaled bitmap (so that it's height <= MAX_HEIGHT). You should use `int totalHeight = scrollView.getChildAt(0).getHeight();` to get a `ScrollView` height. Later you can upscale the bitmap if it becomes smaller. – CoolMind Oct 19 '21 at 15:08
5

This one works for me

To save the bitmap check runtime permission first

 @OnClick(R.id.donload_arrow)
    public void DownloadBitMap()
    {
     if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) 
    {
        downloadData();
                    Log.e("callPhone: ", "permission" );
                } else {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                    Toast.makeText(this, "need permission", Toast.LENGTH_SHORT).show();
                }

            }

To get bitmap

 private void downloadData() {

        ScrollView iv = (ScrollView) findViewById(R.id.scrollView);
        Bitmap bitmap = Bitmap.createBitmap(
                iv.getChildAt(0).getWidth()*2,
                iv.getChildAt(0).getHeight()*2,
                Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bitmap);
        c.scale(2.0f, 2.0f);
        c.drawColor(getResources().getColor(R.color.colorPrimary));
        iv.getChildAt(0).draw(c);
        // Do whatever you want with your bitmap
        saveBitmap(bitmap);

    }

To save the bitmap

 public void saveBitmap(Bitmap bitmap) {
        File folder = new File(Environment.getExternalStorageDirectory() +
                File.separator + "SidduInvoices");
        boolean success = true;
        if (!folder.exists()) {
            success = folder.mkdirs();
        }
        if (success) {
            // Do something on success
        } else {
            // Do something else on failure
        }

        File imagePath = new File(Environment.getExternalStorageDirectory() + "/SidduInvoices/Siddus.png");

        if(imagePath.exists())
        {
            imagePath=new File(Environment.getExternalStorageDirectory() + "/SidduInvoices/Siddus"+custamername.getText().toString()+".png");

        }
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(imagePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            progressBar.cancel();


            final File finalImagePath = imagePath;
            new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
                    .setTitleText("Saved")
                    .setContentText("Do you want to share this with whatsapp")
                    .setCancelText("No,cancel !")
                    .setConfirmText("Yes,share it!")
                    .showCancelButton(true)
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.cancel();
                            shareImage(finalImagePath);
                        }
                    })
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.cancel();

                        }
                    })
                    .show();




        } catch (FileNotFoundException e) {
            Log.e("GREC", e.getMessage(), e);
        } catch (IOException e) {
            Log.e("GREC", e.getMessage(), e);
        }



    }
Saneesh
  • 1,796
  • 16
  • 23
2

You need get the total width and height of the scrollview, or you created viewBitmap is too small to contain the full content of the scrollview.

check this link Android: Total height of ScrollView

Community
  • 1
  • 1
user1203650
  • 300
  • 2
  • 3
1

The issue here is that the only actual pixel content that ever exists is that which is visible on the display screen. Android and other mobile platforms are very careful about memory use and one of the ways a scrolling view can maintain performance is to not draw anything that is offscreen. So there is no "full" bitmap anywhere -- the memory containing the content that moves offscreen is recycled.

elijah
  • 2,904
  • 1
  • 17
  • 21