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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…