2017-01-09 38 views
1

我試圖使用繪圖緩存,使一個編程創建視圖的位圖,如下所示:繪製編程創建視圖爲位圖

LinearLayout view = new LinearLayout(context); 
view.setBackground(context.getResources().getColor(R.color.green)); 
view.setDrawingCacheEnabled(true); 

int width = View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY); 
int height = View.MeasureSpec.makeMeasureSpec(600, View.MeasureSpec.EXACTLY); 
view.measure(w, h); 
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 
view.buildDrawingCache(true); 

Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); 

我期待它輸出一個800x600綠色位圖;相反,我得到一個800x600的白色位圖。我究竟做錯了什麼?

+0

你不能只是像這樣即時調整視圖的大小。系統沒有爲它設置。 –

+0

@GabeSechan:其實應該沒問題。我在儀器測試中已經完成了。 – CommonsWare

+1

「我希望它輸出800x600的綠色位圖」 - 爲什麼?一個'LinearLayout'不是魔法般的綠色,並且在這裏沒有代碼讓它變成綠色。除此之外,你沒有在任何地方繪製它。擺脫所有繪圖緩存的東西,創建一個'Bitmap'支持的'Canvas',並將'draw()'視圖映射到'Canvas'。 「位圖」將包含繪圖的結果。 – CommonsWare

回答

0

由於@CommonsWare,這個工程:

LinearLayout view = new LinearLayout(context); 
    view.setBackgroundColor(context.getResources().getColor(R.color.green)); 
    int width = View.MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY); 
    int height = View.MeasureSpec.makeMeasureSpec(600, View.MeasureSpec.EXACTLY); 
    view.measure(width, height); 

    Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas(bitmap); 
    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 
    view.draw(canvas); 
0

您可以使用下面的代碼來創建位圖編程

int w = WIDTH_PX, h = HEIGHT_PX; 
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types 
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // 
Canvas canvas = new Canvas(bmp); 

希望,這將解決您的問題