1

I am trying to draw a view onto an external canvas using View.draw( Canvas canvas ). For this to work, the view has to have performed a full layout beforehand.

However, my reason for calling View.draw( Canvas canvas ) is so that I can generate a PdfDocument from the view, while leveraging existing widgets instead of custom-drawing everything in my code. In other words, invoke a full layout of the view (and it's children) in memory rather than on screen... if that makes any sense.

I'm hoping to create a view (without rendering it) with fixed height and width, then dumping the view to the PdfDocument page's canvas.

Can this be done and if so, what's the trick?

If not, is there a better way?

El Stepherino
  • 600
  • 6
  • 18

1 Answers1

1

Compared to drawing to screen you need to set Layout Parameters, measure and layout as @CommonsWare says.

In my App I draw a view to save to PNG and to print but you could at the Bitmap to a PDF document as well.

Note this technique does not seem to work well with things that scroll because you get only usually only get what the would be shown on screen.

In my case I have a large TableLayout inside the scrollview, so I draw the TableLayout to the bitmap not the scrollView.

I generate the TableLayout called view then to save to PNG I do the following (this could easily be adapted for a pdf dcoument)

Extract of the code I use (Because I use the same code to actually draw to screen as well once it has been laid out I find by Id exactly what I want to save to PNG)


int tableLayoutId = 1;
float scaleFactor = 0.5f;

TableLayout tableLayout = new TableLayout(DetailedScoresActivity.this);
        tableLayout.setId(tableLayoutId);

// More code to fill out the TableLayout

// .....

// Then Need to full draw this view as it has not been shown in the gui
            tableLayout.setLayoutParams(new TableLayout.LayoutParams(TabLayout.LayoutParams.WRAP_CONTENT,
                    TabLayout.LayoutParams.WRAP_CONTENT));
            tableLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            tableLayout.layout(0, 0, tableLayout.getMeasuredWidth(), tableLayout.getMeasuredHeight());

            Canvas bitmapCanvas = new Canvas();
            Bitmap bitmap = Bitmap.createBitmap(Math.round(tableLayout.getWidth() * scaleFactor), Math.round(tableLayout.getHeight() * scaleFactor), Bitmap.Config.ARGB_8888);

            bitmapCanvas.setBitmap(bitmap);
            bitmapCanvas.scale(scaleFactor, scaleFactor);
            tableLayout.draw(bitmapCanvas);
Andrew
  • 8,198
  • 2
  • 15
  • 35
  • Awesome, man. Since my custom view didn't have a parent and wasn't being shown, I got your code snippet (mixed with my code) working by specifying exact dimensions and using `View.MeasureSpec.EXACTLY` with makeMeasureSpec... – El Stepherino Mar 08 '20 at 01:52