2015-04-02 55 views
0

我試圖在非活動類中獲取視圖並將其轉換爲位圖,這是我的嘗試,但視圖似乎具有0作爲維度。 我只是XML文件:在非Activity類中獲取視圖並將其轉換爲位圖

custom_view.xml

<?xml version="1.0" encoding="utf-8"?> 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="70dp" 
    android:layout_height="70dp" 
    android:background="@drawable/pin_events" 
    android:id="@+id/rel"> 

    <ImageView 
     android:layout_width="50dp" 
     android:layout_height="50dp" 
     android:scaleType="centerInside" 
     android:src="@drawable/sport" 
     android:layout_centerHorizontal="true"/> 

</RelativeLayout> 

這裏是我試圖讓一個位圖:

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View v = inflater.inflate(R.layout.custom_view, null); 

RelativeLayout view = (RelativeLayout) v.findViewById(R.id.rel); 
view.setDrawingCacheEnabled(true); 
view.buildDrawingCache(); 

Bitmap bm = view.getDrawingCache(); 
+0

爲什麼不使用'位圖位圖= BitmapFactory.decodeResource(context.getResource s(), R.drawable.resource);'直接從資源中獲取位圖? – 2015-04-02 15:18:25

+0

@EvripidisDrakos它不適用於佈局。 – 2015-04-02 15:19:23

+0

啊,你想把整個視圖轉換成圖像嗎?我不知道這是否可能.. – 2015-04-02 15:20:30

回答

1

你能嘗試以下方法:

view.setDrawingCacheEnabled(true); 

view.setLayoutParams(new ViewGroup.LayoutParams(0, 0)); 

view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
       MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); 

view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 

view.buildDrawingCache(true); 

Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); 

view.setDrawingCacheEnabled(false); // clear drawing cache 
+0

我非常愛你 – 2015-04-02 15:26:38

+0

很高興它工作 – 2015-04-02 15:31:47