android 截取布局内容并生成图片,截取长图,LinearLayout WebView等皆适用,保存图片到相册,并通知相册更新
时间:02-13来源:作者:点击数:50
1.截图布局(控件)内容并生成Bitmap
-
-
- public static String captureWebView(Context context, ViewGroup viewGroup, String fileName) {
- String filePath="";
-
- viewGroup.measure(View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
- View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
-
- viewGroup.layout(0, 0, viewGroup.getMeasuredWidth(), viewGroup.getMeasuredHeight());
-
- viewGroup.setDrawingCacheEnabled(true);
-
- viewGroup.buildDrawingCache();
-
- Bitmap picture = Bitmap.createBitmap(viewGroup.getMeasuredWidth(),
- viewGroup.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
-
- Canvas canvas = new Canvas(picture);
- Paint paint = new Paint();
-
- canvas.drawBitmap(picture, 0, viewGroup.getMeasuredHeight(), paint);
-
- viewGroup.draw(canvas);
- if (null != picture) {
- filePath= saveImageToGallery(context, picture,fileName,false);
- return filePath;
- } else {
- ToastUtils.showShort("出错啦!");
- return filePath;
- }
- }
2.保存图片到相册,并通知相册更新
-
-
- public static String saveImageToGallery(Context context, Bitmap bmp, String fileName, boolean isNotify) {
-
- File appDir = new File(Constant.WALLPAPER_IMAGE_PATH);
- if (!appDir.exists()){
- appDir.mkdir();
- Log.e(TAG, "saveImageToGallery:文件夹不存在 "+appDir.getPath() );
- return "";
- }
-
- File file = new File(appDir,fileName);
- if (!file.exists()){
- ToastUtils.showShort("文件不存在");
- Log.e(TAG, "saveImageToGallery:文件不存在 "+file.getPath() );
- try {
- file.createNewFile();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- return "";
- }
- try {
- FileOutputStream fos = new FileOutputStream(file);
- bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
- fos.flush();
- fos.close();
- } catch (FileNotFoundException e) {
- Log.e(TAG, "saveImageToGallery1: "+e.toString() );
- e.printStackTrace();
- } catch (IOException e) {
- Log.e(TAG, "saveImageToGallery2: "+e.toString() );
- e.printStackTrace();
- }
-
- if (isNotify){
-
- try {
- MediaStore.Images.Media.insertImage(context.getContentResolver(),
- file.getAbsolutePath(), fileName, null);
- } catch (FileNotFoundException e) {
- Log.e(TAG, "saveImageToGallery3: "+e.toString() );
- e.printStackTrace();
- return "";
- }
- context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
- }
- return file.getPath();
- }