我想将Android View转换为Drawable。
我尝试以下方法:
View view1;
view1 = getLayoutInflater().inflate(R.layout.layout1, null);
view1.setDrawingCacheEnabled(true);
((TextView)(view1.findViewById(R.id.txt_number))).setText("98");
view1.setLayoutParams(new MapView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, getPoint(23.01, 72.55), MapView.LayoutParams.BOTTOM_CENTER));
mapView.addView(overlayPin1);
Log.d("view", "000");
if(view1!=null)
{
Log.d("view", "111");
System.out.println("view is not null.....");
view1.buildDrawingCache();
Bitmap bm = view1.getDrawingCache();
Log.d("view", "222");
try
{
Log.d("view", "333");
//if(bm!=null)
//{
Log.d("view", "444");
String dir = Environment.getExternalStorageDirectory().toString();
System.out.println("bm is not null.....");
OutputStream fos = null;
File file = new File(dir,"sample.JPEG");
fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bm.compress(Bitmap.CompressFormat.JPEG, 50, bos);
bos.flush();
bos.close();
Log.d("view", "555");
//}
}
catch(Exception e)
{
Log.d("view", "666");
System.out.println("Error="+e);
e.printStackTrace();
}
}
但是我一直得到空位图。
答案 0 :(得分:2)
当View
完全加载/完成加载时,
view.buildDrawingCache();
要获得Drawable,
Drawable drawable = new BitmapDrawable(view.getDrawingCache());
答案 1 :(得分:2)
您需要调用view1.measure(...),否则视图不知道如何绘制自己,因为您没有将它添加到视图层次结构中。
final int height = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
final int width = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
view1.measure(width, height);