Search code examples
androidbitmapscrollview

How to convert all content in a scrollview to a bitmap?


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

Solution

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