2

我想将 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();
                }
            }  

但我总是得到空位图。

4

2 回答 2

2

You need to call view1.measure(...) or else the view doesn't know how to draw itself because you are not adding it to the view hierarchy.

final int height = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
final int width = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
view1.measure(width, height);
于 2012-05-02T11:50:43.007 回答
2

当您View完全加载/完成加载时,

view.buildDrawingCache();

要使用 Drawable,

Drawable drawable = new BitmapDrawable(view.getDrawingCache());
于 2012-05-02T11:49:01.527 回答