最近收到一个分享图需求,需要将当前页面进行截取后,生成一个Bitmap保存到相册或分享到微信/朋友圈。
而分享时需要隐去页面上很多按钮和文字,如果直接使用DrawingCache在保存的时候用户会看到页面元素消失再显示,那么这样体验会很差,所以使用另一种方式来实现。
1 2 3 4 5 6 7
| public static Bitmap createBitmapFromView(View view) { view.setDrawingCacheEnabled(true); view.buildDrawingCache(true); Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); view.setDrawingCacheEnabled(false); return bitmap; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
public Bitmap createBitmapFromInvisibleView(View v, int dpWidth, int dpHeight) { int measuredWidth = View.MeasureSpec.makeMeasureSpec(DisplayUtils.dp2px(dpWidth), View.MeasureSpec.EXACTLY); int measuredHeight = View.MeasureSpec.makeMeasureSpec(DisplayUtils.dp2px(dpHeight), View.MeasureSpec.EXACTLY); v.measure(measuredWidth, measuredHeight); v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight()); Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bmp); c.drawColor(Color.WHITE); v.draw(c); return bmp; }
|
- 补充:将Bitmap位图保存到相册中的方法
如果需要将图片保存到相册中,可以参考此方法,支持版本Android-Q
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
| public static String saveBitmapAndroidQ(Context context, String dir, Bitmap b) { long dataTake = System.currentTimeMillis(); String jpegName = "IMG_" + dataTake + ".jpg";
ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DISPLAY_NAME, jpegName); values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/" + dir);
Uri external; ContentResolver resolver = context.getContentResolver(); String status = Environment.getExternalStorageState(); if (status.equals(Environment.MEDIA_MOUNTED)) { external = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else { external = MediaStore.Images.Media.INTERNAL_CONTENT_URI; }
Uri insertUri = resolver.insert(external, values); if (insertUri == null) { return ""; } OutputStream os; try { os = resolver.openOutputStream(insertUri); b.compress(Bitmap.CompressFormat.JPEG, 100, os); if (os != null) { os.flush(); os.close(); } return insertUri.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } }
|
参考: