2016-02-05 63 views
0

我在android中使用視圖,我需要將其轉換爲位圖而不將其添加到活動中。如何將視圖轉換爲位圖而不添加到Android的UI中

view.setDrawingCacheEnabled(true); 
    Bitmap bitmap= view.getDrawingCache(); 

它將位圖返回爲null。

另外我已經嘗試了view.buildDrawingCache()方法,但仍然getDrawingCache()返回null。

在此先感謝。

回答

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); // this creates a MUTABLE bitmap 
Canvas canvas = new Canvas(bmp); 

現在你需要繪製您在此位圖查看。 使用下面碼本

LinearLayout layout = new LinearLayout(getContext()); 

TextView textView = new TextView(getContext()); 
int padding = 4; 
textView.setPadding(padding, padding, padding, padding); 
textView.setVisibility(View.VISIBLE); 
textView.setText("Hello how are you"); 
layout.addView(textView); 
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10); 

layout.measure(canvas.getWidth(), canvas.getHeight()); 
layout.layout(0, 0, canvas.getWidth(), canvas.getHeight()); 
layout.draw(canvas); 

現在您的視圖被轉換成位圖(BMP)。

相關問題