如何将LinearLayout转换为图像

7
我想将完整的 layout 和其中的内容 (views) 转换为可绘制的图像?

5
可能重复:https://dev59.com/cG025IYBdhLWcg3w1JeG您可以使用以下代码将View转换为Drawable:public static Drawable convertViewToDrawable(View view) { Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); view.draw(canvas); return new BitmapDrawable(view.getResources(), bitmap); }请注意,此方法只能在View已经测量和布局之后才能正常工作。 - eric.itzhak
1个回答

31
尝试以下代码:
public class AndroidWebImage extends Activity {

ImageView bmImage; 
LinearLayout view;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      view = (LinearLayout)findViewById(R.id.screen);
      bmImage = (ImageView)findViewById(R.id.image);

      view.setDrawingCacheEnabled(true);
      // this is the important code :)  
      // Without it the view will have a dimension of 0,0 and the bitmap will be null          

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

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

      view.buildDrawingCache(true);
      Bitmap b = Bitmap.createBitmap(view.getDrawingCache());
      view.setDrawingCacheEnabled(false); // clear drawing cache

      bmImage.setImageBitmap(b);   

};


}

仔细看,你必须使用:

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

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

我使用了以下的 main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
   android:id="@+id/screen"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  />
<ImageView
  android:id="@+id/image"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
/>
</LinearLayout>

结果是:

图片描述 参考


你救了我,伙计。 - aida

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接