简体   繁体   中英

How to render an android view to canvas WITHOUT rendering it first (i.e. without full layout)

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM