Android 对 屏幕内的 View 截图的 3 个方法
做项目刚刚用到了这个,正好做个总结:
第一种:利用view自带的DrawingCache功能
1 /** 2 * 截图 3 * @param view 4 * @return 5 */ 6 public Bitmap screeShot2(View view){ 7 view.setDrawingCacheEnabled(true); 8 return view.getDrawingCache(); 9 }
这种方法最简单,但是有个问题,就是得到的图像是严重压缩过的,图片质量最差。
原因是view.getDrawingCache()等同于view.getDrawingCache(false)
官方API:Note about auto scaling in compatibility mode: When auto scaling is not enabled, this method will create a bitmap of the same size as this view. Because this bitmap will be drawn scaled by the parent ViewGroup, the result on screen might show scaling artifacts. To avoid such artifacts, you should call this method by setting the auto scaling to true. Doing so, however, will generate a bitmap of a different size than the view. This implies that your application must be able to handle this size.
也就是说如果设置为false,会被parent压缩,从而得到的是scaling artifacts,只有设置为true才可以,但是如果这样设置就需要你自己去处理图片的尺寸。
第二种:使用规定好的参数创建事先创建好一个bitmap,然后画到canvas中去
1 /** 2 * 截图 3 * @param view 4 * @return 5 */ 6 public Bitmap screenShot(View view) { 7 Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), 8 view.getHeight(), Config.ARGB_8888); 9 Canvas canvas = new Canvas(bitmap); 10 view.draw(canvas); 11 return bitmap; 12 }
这个方法得到的图片质量也是压缩过的,但质量要比第一种好。
第三种:和第二种类似,只不过多了自己测量的view
1 /** 2 * 截图 3 * @param context 4 * @param v 5 * @return 6 */ 7 public static Bitmap loadBitmapFromView(Context context, View v) { 8 DisplayMetrics dm = context.getResources().getDisplayMetrics(); 9 v.measure(MeasureSpec.makeMeasureSpec(dm.widthPixels, MeasureSpec.EXACTLY), 10 MeasureSpec.makeMeasureSpec(dm.heightPixels, MeasureSpec.EXACTLY)); 11 v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); 12 Bitmap returnedBitmap = Bitmap.createBitmap(v.getMeasuredWidth(), 13 v.getMeasuredHeight(), Bitmap.Config.ARGB_8888); 14 Canvas c = new Canvas(returnedBitmap); 15 v.draw(c); 16 return returnedBitmap; 17 }
这个方法得到的图像质量最好
浙公网安备 33010602011771号