如何将scrollview中的所有内容转换为位图?

时间:2012-01-05 06:20:21

标签: android bitmap scrollview

我使用下面的代码进行转换,但似乎只能获取显示屏幕中的内容而无法获取不在显示屏幕中的内容。

有没有办法让所有内容都不滚动?

Bitmap viewBitmap = Bitmap.createBitmap(mScrollView.getWidth(),mScrollView.getHeight(),Bitmap.Config.ARGB_8888);  
Canvas canvas = new Canvas(viewBitmap); 
mScrollView.draw(canvas);

5 个答案:

答案 0 :(得分:25)

我们可以使用下面显示的代码将scrollView的所有内容转换为位图图像

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

答案 1 :(得分:7)

Pops的答案非常好,但在某些情况下,您可能必须创建一个非常大的位图,在创建位图时可能会触发OutOfMemoryException。

所以我做了一点优化,以便轻轻地记忆:)

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

答案 2 :(得分:3)

这个适用于我

首先保存位图检查运行时权限

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

            }

获取位图

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

    }

保存位图

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



    }

答案 3 :(得分:1)

这里的问题是,唯一存在的实际像素内容是在显示屏上可见的内容。 Android和其他移动平台对内存使用非常谨慎,滚动视图可以保持性能的一种方法是不绘制任何屏幕外的内容。因此,任何地方都没有“完整”位图 - 包含移动到屏幕外的内容的内存将被回收。

答案 4 :(得分:1)

您需要获取scrollview的总宽度和高度,否则您创建的viewBitmap太小而无法包含scrollview的完整内容。

检查此链接 Android: Total height of ScrollView