2017-08-01 161 views
0

所以我叫demo_text.xml轉換外部XML佈局爲位圖使用佈局充氣

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:id="@+id/screen"> 

<TextView 
    android:id="@+id/textToDisplay" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:text="Hello World" 
</FrameLayout> 

我想這demo_text轉換爲位圖下面的佈局。這是我的創建:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    View inflatedFrame = getLayoutInflater().inflate(R.layout.demo_text, null); 
    FrameLayout frameLayout = (FrameLayout) inflatedFrame.findViewById(R.id.screen) ; 
    frameLayout.setDrawingCacheEnabled(true); 
    frameLayout.buildDrawingCache(); 
    Bitmap bm = frameLayout.getDrawingCache(); 

} 

我想位圖是整個佈局,但位圖總是返回null。

+0

爲什麼你使用'FrameLayout'在你的活動視圖的根源在哪裏?你可以在'Fragment'中使用'FrameLayout'。無論如何,你可以嘗試在'inflate'方法而不是'null'的第二個參數處傳遞'ViewGroup'根。 (不知道這是否工作) – lalosoft

+0

重複https://stackoverflow.com/a/12406426/2700586 – Mani

回答

0

你可以用下面的代碼嘗試

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
FrameLayout frameLayout = (FrameLayout) inflatedFrame.findViewById(R.id.screen); 
Bitmap b = loadBitmapFromView(frameLayout); 
} 

使用belolw方法來獲取位圖。

public Bitmap loadBitmapFromView(View v) { 
    Bitmap b = Bitmap.createBitmap(v.getLayoutParams().width, 
    v.getLayoutParams().height, Bitmap.Config.ARGB_8888);     
    Canvas c = new Canvas(b); 
    v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom()); 
    v.draw(c); 
    return b; 
} 
3

下面的代碼工作:

View inflatedFrame = getLayoutInflater().inflate(R.layout.demo_text, null); 
    FrameLayout frameLayout = (FrameLayout) inflatedFrame.findViewById(R.id.screen) ; 
    frameLayout.setDrawingCacheEnabled(true); 
    frameLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), 
      View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); 
    frameLayout.layout(0, 0, frameLayout.getMeasuredWidth(), frameLayout.getMeasuredHeight()); 
    frameLayout.buildDrawingCache(true); 
    final Bitmap bm = frameLayout.getDrawingCache();