1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| public static Bitmap convertViewToBitMap(View view){ // 打开图像缓存 view.setDrawingCacheEnabled(true); // 必须调用measure和layout方法才能成功保存可视组件的截图到png图像文件 // 测量View大小 int i = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int n = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); view.measure(i, n); // 发送位置和尺寸到View及其所有的子View view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); // 获得可视组件的截图 Bitmap bitmap = view.getDrawingCache(); return bitmap; }
/** * 该方法会报错,java.lang.IllegalArgumentException: width and height must be > 0 */ public static Bitmap getBitmapFromView(View view){ Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(returnedBitmap); Drawable bgDrawable = view.getBackground(); if (bgDrawable != null){ bgDrawable.draw(canvas); } else{ canvas.drawColor(Color.WHITE); } view.draw(canvas); return returnedBitmap; }
//该方法验证可以 public static Bitmap loadBitmapFromView(View v) { v.measure(0, 0); int w = v.getMeasuredWidth(); int h = v.getMeasuredHeight(); if (w <= 0 || h <= 0) { DisplayMetrics metric = new DisplayMetrics(); w = metric.widthPixels;// 屏幕宽度(像素) h = metric.heightPixels;// 屏幕高度(像素) } Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bmp); c.drawColor(Color.WHITE); //如果不设置canvas画布为白色,则生成透明 v.layout(0, 0, w, h); v.draw(c); return bmp; }
|