How to convert linearlayout to image

后端 未结 1 1070
醉话见心
醉话见心 2020-12-15 13:57

I want to convert the full layout with it\'s contents (views) into Drawable image?

1条回答
  •  一向
    一向 (楼主)
    2020-12-15 14:56

    Try the following code:


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

    Take a good look, you have to use:

     view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    
     view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 
    

    I used the following main.xml:

    
    
    
    
    
    

    The outcome is:

    enter image description here Reference

    0 讨论(0)
提交回复
热议问题