How to convert all content in a scrollview to a b

2020-02-02 12:16发布

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);

5条回答
我命由我不由天
2楼-- · 2020-02-02 12:48

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;
}
查看更多
冷血范
3楼-- · 2020-02-02 12:50

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);
        }



    }
查看更多
smile是对你的礼貌
4楼-- · 2020-02-02 12:51

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

查看更多
做个烂人
5楼-- · 2020-02-02 13:01

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.

查看更多
唯我独甜
6楼-- · 2020-02-02 13:07

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;
}
查看更多
登录 后发表回答