与在屏幕上绘图相比,您需要像@CommonsWare 所说的那样设置布局参数、测量和布局。
在我的应用程序中,我绘制了一个视图以保存为 PNG 并进行打印,但您也可以在位图上将其保存为 PDF 文档。
请注意,这种技术似乎不适用于滚动的内容,因为您通常只能获得将在屏幕上显示的内容。
在我的例子中,我在滚动视图中有一个大的 TableLayout,所以我将 TableLayout 绘制到位图而不是滚动视图。
我生成名为 view 的 TableLayout 然后保存到 PNG 我执行以下操作(这很容易适应 pdf 文件)
我使用的代码的摘录(因为我使用相同的代码来实际绘制到屏幕上,一旦布局完成,我通过 Id 找到我想要保存到 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);