Android获取View的内容图片

  • Post author:
  • Post category:其他


1 获取当前可见的View的图片,类似于手机截屏

View dView = getWindow().getDecorView();//获取DecorView
dView.setDrawingCacheEnabled(true);//生成View的副本,是一个Bitmap
Bitmap bmp = dView.getDrawingCache();//获取View的副本,就是这个View上面所显示的任何内容


2 获取任意View的内容图片

Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);//使用bitmap构建一个Canvas,绘制的所有内容都是绘制在此Bitmap上的
Drawable bgDrawable = v.getBackground();
bgDrawable.draw(c);//绘制背景
view.draw(c);//绘制前景
return bitmap;

如果是ListView,ScrollView,Webview等高度不固定的View,还需要手动计算出来高度来创建Bitmap,其他步骤相同

for (int i = 0; i < listView.getChildCount(); i++) {
    h += listView.getChildAt(i).getHeight();
}
// 创建对应大小的bitmap
bitmap = Bitmap.createBitmap(listView.getWidth(), h,
        Bitmap.Config.ARGB_8888);

示例代码

//组合view
private Bitmap combineView(View topView, WebView centerView, View bottomView) {

    float topWidth = topView.getWidth();
    float topHeight = topView.getHeight();

    float centerWidth = centerView.getWidth();
    float centerHeight = centerView.getContentHeight() * centerView.getScale();

    float bottomWidth = bottomView.getWidth();
    float bottomHeight = bottomView.getHeight();

    float width = Math.max(topWidth, Math.max(centerWidth, bottomWidth));//取最大的宽度作为最终宽度
    float height = topHeight + centerHeight + bottomHeight;//计算总高度

    Bitmap topBitmap = Bitmap.createBitmap((int) width, (int) topHeight, Bitmap.Config
            .ARGB_8888);//顶部图片
    topView.draw(new Canvas(topBitmap));

    Bitmap centerBitmap = Bitmap.createBitmap((int) width, (int) centerHeight, Bitmap.Config
            .ARGB_8888);//中部图片
    centerView.draw(new Canvas(centerBitmap));

    Bitmap bottomBitmap = Bitmap.createBitmap((int) width, (int) bottomHeight, Bitmap.Config
            .ARGB_8888);//底部图片
    bottomView.draw(new Canvas(bottomBitmap));

    Bitmap bitmap = Bitmap.createBitmap((int) width, (int) height, Bitmap.Config.ARGB_8888);//底图
    Canvas canvas = new Canvas(bitmap);//画布
    Paint paint = new Paint();

    canvas.drawBitmap(topBitmap, 0, 0, paint);//画顶部
    canvas.drawBitmap(centerBitmap, 0, topHeight, paint);//画中间
    canvas.drawBitmap(bottomBitmap, 0, topHeight + centerHeight, paint);//画底部

    return bitmap;
}



版权声明:本文为qq_15771061原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。