android - 如何将膨胀的 View 转换为位图?

标签 android

我有一个 View 是从布局中膨胀的:

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

现在我想将膨胀的 View 转换为位图

我该怎么办?

最佳答案

您可以按如下方式完成:

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

最后,您得到了膨胀后的 tagView位图

关于android - 如何将膨胀的 View 转换为位图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12403193/

相关文章:

android - 实现 OnLongClickListener 时 ExpandableListView 不扩展

android - 在设备中保存凭据的最佳方法

android - 对于 MySQL 请求,是否有比 ASyncTask 更好的类或库?

java - 为什么我无法访问java中内部类的方法?

android - REQUEST_DENIED 使用 Google Places API 浏览器 key 或应用程序 key ?

android - 如何删除数据库中的错误 sqlite 返回 : error code = 1, msg = table Customer_details_table has no column named "Card Number"

java - 更新库的 Gradle 同步项目

android - “Gradle error after Android Studio update”

android - Activity 和线程处理

java - 为什么 Android Studio 在 Reformatting the code 上导入完整包