2012-05-02 48 views
2

我想將Android視圖轉換爲Drawable。如何將視圖轉換爲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(); 
       } 
      } 

但所有的時間,我得到了空位圖。

回答

2

當你View被完全加載/裝完,

view.buildDrawingCache(); 

要獲得繪製對象使用,

Drawable drawable = new BitmapDrawable(view.getDrawingCache()); 
+1

我總是得到一個空繪製因爲view.getDrawingCache()返回null –

+0

任何想法,爲什麼我總是得到繪製Null值? –

+0

你使用view.setDrawingCacheEnabled(true); view.buildDrawingCache(); – Kowlown

2

你需要調用view1.measure(...),或者認爲沒有按不知道如何繪製自己,因爲您沒有將它添加到視圖層次結構中。

final int height = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY); 
final int width = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY); 
view1.measure(width, height); 
+0

他可以將它添加到佈局某處,但這只是甜蜜的。 – 2016-07-18 15:37:05

相關問題