-
使用截屏,然后保存图片
-
如果要保存的布局正好是撑满这个屏幕,那可以使用截屏的方式来保存图片;
-
如果只是屏幕的某一个部分,那才用截屏后,还得对截屏后的图片进行二次裁剪,而且要裁剪的坐标点也比较难正确得出;
-
要保存的布局大于当前屏幕,那就得多次截屏,然后再把几个截屏拼接起来,费时费力。
-
启用View自带绘制缓存(这个名字估计不太合适)
Google估计早就想到了这个问题,在查看View的源码的时候,发现View本身有两个方法很有意思。
一是:setDrawingCacheEnabled(boolean enabled),这个方法设置为true,就可以生成位图的副本(原话:This API can be used to manually generate a bitmap copy of this view, by setting the flag to <code>true</code> and calling {@link #getDrawingCache()}.);
二是:getDrawingCache(),这个方法其实是调用的getDrawingCache(false),这个方法返回的一个绘制此View时的视图缓存Bitmap(原话:Returns the bitmap in which this view drawing is cached.);
知道了这两个方法就可以将任意XML任意模块的View给生成图片,是不是很简单,如下: -
父布局(要生成图片的布局,下边同)开启绘图缓存;
-
计算父布局宽高;
-
父布局设置layout;
-
用Bitmap.createBitmap(获取父布局到的cache)生成Bitmap;
-
关闭DrawingCache;
-
接下来是保存到本地还是直接设置给ImageView自己决定了。
点击保存图片按钮,执行如下代码,将布局保存成Bitmap设置给“小兵”下边那个ImageView,click的代码如下:
ll.setDrawingCacheEnabled(true);
ll.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
ll.layout(0, 0, ll.getMeasuredWidth(), ll.getMeasuredHeight());
Bitmap bitmap = Bitmap.createBitmap(ll.getDrawingCache());
ll.setDrawingCacheEnabled(false);
iv.setImageBitmap(bitmap);
运行前:

点击保存图片后:

网友评论
public Bitmap getBitmap(View view) {
Bitmap bitmap = null;
int width = view.getRight() - view.getLeft();
int height = view.getBottom() - view.getTop();
final boolean opaque = view.getDrawingCacheBackgroundColor() != 0 || view.isOpaque();
Bitmap.Config quality;
if (!opaque) {
switch (view.getDrawingCacheQuality()) {
case DRAWING_CACHE_QUALITY_AUTO:
case DRAWING_CACHE_QUALITY_LOW:
case DRAWING_CACHE_QUALITY_HIGH:
default:
quality = Bitmap.Config.ARGB_8888;
break;
}
} else {
quality = Bitmap.Config.RGB_565;
}
bitmap = Bitmap.createBitmap(getResources().getDisplayMetrics(),
width, height, quality);
bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
if (opaque) bitmap.setHasAlpha(false);
boolean clear = view.getDrawingCacheBackgroundColor() != 0;
Canvas canvas = new Canvas(bitmap);
if (clear) {
bitmap.eraseColor(view.getDrawingCacheBackgroundColor());
}
view.computeScroll();
final int restoreCount = canvas.save();
canvas.translate(-view.getScrollX(), -view.getScrollY());
view.draw(canvas);
canvas.restoreToCount(restoreCount);
canvas.setBitmap(null);
return bitmap;
}