如何将一个已填充的View转换为位图?

7

我有一个视图是从布局中填充的:

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

现在我想将充气的视图转换为位图。

我该怎么做?

1个回答

9
你可以按照以下步骤完成:

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

最终,您已经得到了填充的tagViewbitmap

由于tagView.getLayoutParams().width和tagView.getLayoutParams().height返回NullPointerException,导致程序崩溃。 - user1531240
tagView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); 抛出 NullPointExcetion 异常 - user1531240
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)的结果是0。 - user1531240
位图为空。 - mobiledev Alex

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