2016-02-05 57 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)。

相关问题