我正在寻找解决方案,最终设法提出了我自己的解决方案,其实很简单。
就我而言,我有一个LinearLayout
,其中包含一些View
元素,其中有些元素有时不在屏幕上,垂直低于屏幕边界的末端。我能够将View
保存为位图(请参阅下面的loadBitmapFromView()
),但当它延伸到屏幕底部时遇到问题。
我的解决方案是将LinearLayout
组合为ScrollView
组合的一部分。
例如
此:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/my_linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<!-- Some Views added here at runtime -->
</LinearLayout>
变成了:
注意使用wrap_content
确保滚动型扩展到内容的高度。
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroll"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:id="@+id/my_linear_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<!-- Some Views added here at runtime -->
</LinearLayout>
</ScrollView>
这似乎保证了屏幕外的项目可以手动布局时,我想的View
保存为位图。我用下面的方法保存位图。我很早就发现了这一点,但我似乎无法找到正确引用它的问题(无论你是谁 - 谢谢!)。
对于以下方法,我通过参考上面的LinearLayout
(my_linear_layout
)。
public static Bitmap loadBitmapFromView(View view) {
Bitmap bitmap = null;
// width measure spec
int widthSpec = View.MeasureSpec.makeMeasureSpec(
view.getMeasuredWidth(), View.MeasureSpec.AT_MOST);
// height measure spec
int heightSpec = View.MeasureSpec.makeMeasureSpec(
view.getMeasuredHeight(), View.MeasureSpec.AT_MOST);
// measure the view
view.measure(widthSpec, heightSpec);
// set the layout sizes
int left = view.getLeft();
int top = view.getTop();
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
int scrollX = view.getScrollX();
int scrollY = view.getScrollY();
view.layout(left, top, width + left, height + top);
// create the bitmap
bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
Bitmap.Config.ARGB_8888);
// create a canvas used to get the view's image and draw it on the
// bitmap
Canvas c = new Canvas(bitmap);
// position the image inside the canvas
c.translate(-view.getScrollX(), -view.getScrollY());
// get the canvas
view.draw(c);
return bitmap;
}
感谢创造者为您的快速响应。 view.getDrawable()方法仅由Views支持,它像ImageView那样“持有”一个前景图片。像RelativeLayouts,LinearLayouts,TextViews等所有其他视图不支持此方法。大多数互联网论坛推荐方法1或2(见我的文章),以便从视图制作位图截图(即背景和前景)。对于超大视图,问题仍未解决。任何其他想法? – 2012-02-15 18:54:59
那么,我已经提到,view.getDrawable()不支持在帖子本身的每个视图。 这两种方法给出了完整的图像,包括屏幕外部分,可以尝试使用画布和自定义视图将这两个单独的图像放在一个视图中(如果forground一个是透明背景png图像),并获取虽然我从来没有尝试过,所以不能说出这将如何工作,但如果你能遵循,你可能会实现你所需要的。 – noob 2012-02-15 19:15:46
getDrawingCache()方法旨在仅给出屏幕上的图像,所以我不认为这适用于您。使用getDrawingCache(true)可能适合你。 另一个想法可能是使用LayoutParams调整视图以适合屏幕,然后从那里获取绘图缓存。 – noob 2012-02-15 19:19:46