[英]How to render an android view to canvas WITHOUT rendering it first (i.e. without full layout)
我正在嘗試使用View.draw( Canvas canvas )
在外部畫布上繪制視圖。 為此,視圖必須事先執行完整的布局。
但是,我調用View.draw( Canvas canvas )
是我可以從視圖生成 PdfDocument,同時利用現有的小部件而不是在我的代碼中自定義繪制所有內容。 換句話說,在內存中而不是在屏幕上調用視圖(及其子視圖)的完整布局……如果這有意義的話。
我希望創建一個具有固定高度和寬度的視圖(不渲染它),然后將視圖轉儲到 PdfDocument 頁面的畫布。
這可以做到嗎?如果可以,有什么訣竅?
如果沒有,有沒有更好的方法?
與繪制到屏幕相比,您需要像@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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.