Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a inflated View to Bitmap?

Tags:

android

I have a View is inflate from a layout:

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View tagView = inflater.inflate(R.layout.activity_main, null);
TextView name = (TextView) tagView.findViewById(R.id.textView1);
name.setText("hello");

Now i want to covert the inflated view into Bitmap

How should i do?

like image 902
user1531240 Avatar asked Sep 13 '12 09:09

user1531240


1 Answers

You may get it done as below:

//first, View preparation
LayoutInflater inflater =
   (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View tagView = inflater.inflate(R.layout.activity_main, null);
TextView name = (TextView) tagView.findViewById(R.id.textView1);
name.setText("hello");


//second, set the width and height of inflated view
tagView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
tagView.layout(0, 0, tagView.getMeasuredWidth(), tagView.getMeasuredHeight()); 


//third, finally conversion
final Bitmap bitmap = Bitmap.createBitmap(tagView.getMeasuredWidth(),
tagView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
tagView.draw(canvas);

Finally, you've got bitmap of your inflated tagView.

like image 175
waqaslam Avatar answered Oct 14 '22 23:10

waqaslam