我将尝试解释我究竟需要做什么。
我有 3 个单独的屏幕,分别是 A、B、C。还有另一个称为 HomeScreen 的屏幕,其中所有 3 个屏幕位图都应显示在画廊 View 中,用户可以选择他想去哪个 View 。
通过仅将所有代码放在 HomeScreen Activity 中,我已经能够获取所有 3 个屏幕的位图并将其显示在画廊 View 中。现在,这使代码复杂了很多,我想简化它。
那么,我可以从 HomeScreen 调用另一个 Activity 并且不显示它,而只获取该屏幕的位图。例如,假设我只调用 HomeScreen 并且它调用 Activity A、B、C 并且没有显示来自 A、B、C 的任何 Activity。它只是通过 getDrawingCache() 给出该屏幕的位图。然后我们可以在 HomeScreen 的 Gallery View 中显示这些位图。
我希望我已经非常清楚地解释了这个问题。
请让我知道这是否真的可行。
最佳答案
有办法做到这一点。你必须创建一个位图和一个 Canvas 并调用 view.draw(canvas);
代码如下:
public static Bitmap loadBitmapFromView(View v) {
Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width, v.getLayoutParams().height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
return b;
}
如果 View 在其大小之前未显示,则它的大小将为零。可以这样测量:
if (v.getMeasuredHeight() <= 0) {
v.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Bitmap b = Bitmap.createBitmap(v.getMeasuredWidth(), v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
v.draw(c);
return b;
}
编辑:根据 this post , 将 WRAP_CONTENT
作为值传递给 makeMeasureSpec()
没有任何好处(尽管对于某些 View 类它确实有效),并且推荐的方法是:
// Either this
int specWidth = MeasureSpec.makeMeasureSpec(parentWidth, MeasureSpec.AT_MOST);
// Or this
int specWidth = MeasureSpec.makeMeasureSpec(0 /* any */, MeasureSpec.UNSPECIFIED);
view.measure(specWidth, specWidth);
int questionWidth = view.getMeasuredWidth();
关于android - 将 View 转换为位图而不在 Android 中显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2801116/