使用布局充气器将外部XML布局转换为位图

时间:2017-08-01 00:23:00

标签: android layout bitmap views

所以我有以下布局叫做demo_text.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转换为Bitmap。这是我的onCreate:

@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();

}

我希望位图是整个布局,但Bitmap总是返回null。

2 个答案:

答案 0 :(得分:6)

以下代码有效:

    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();

答案 1 :(得分: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;
}