第一种: 从显示缓存中去获取图片,前提是该view必须可见
第二种: 通过画布canvas方式获取,可以在不可见的状态下获取bitmap,不过,相对第一种较耗资源.
ImageView v = new ImageView(this);
v.setBackgroundResource(R.drawable.icon);
v.buildDrawingCache(true);
v.buildDrawingCache();
Bitmap bm = v.getDrawingCache();
第二种: 通过画布canvas方式获取,可以在不可见的状态下获取bitmap,不过,相对第一种较耗资源.
/**
* 把View绘制到Bitmap上
*
* @param view 需要绘制的View
* @param width 该View的宽度
* @param height 该View的高度
* @return 返回Bitmap对象
*/
private Bitmap getBitmapFromView(View view, int width, int height)
{
int widthSpec = View.MeasureSpec.makeMeasureSpec(width,
View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(height,
View.MeasureSpec.EXACTLY);
view.measure(widthSpec, heightSpec);
view.layout(0, 0, width, height);
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.TRANSPARENT);
canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG
| Paint.FILTER_BITMAP_FLAG));
view.draw(canvas);
return bitmap;
}