码迷,mamicode.com
首页 > 移动开发 > 详细

Android Webview 保存为图片

时间:2015-05-27 12:19:42      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

/**
	 * @param view, the View you want to screenshot, such as WebView, etc.
	 * @param width, screenshot's width.
	 * @param height, screenshot's height.
	 * @param scroll, true if you want to start capture from currently scroll position.
	 * @param config, the Bitmap.Config, such as ARGB_8888, etc.
	 *
	 * @return the screenshot's Bitmap
	 */
	public static Bitmap capture(View view, float width, float height, boolean scroll, Bitmap.Config config) {
	    if (!view.isDrawingCacheEnabled()) {
	        view.setDrawingCacheEnabled(true);
	    }
	    Bitmap bitmap = Bitmap.createBitmap((int) width, (int) height, config);
	    bitmap.eraseColor(Color.WHITE);
	    Canvas canvas = new Canvas(bitmap);
	    int left = view.getLeft();
	    int top = view.getTop();
	    if (scroll) {
	        left = view.getScrollX();
	        top = view.getScrollY();
	    }
	    int status = canvas.save();
	    canvas.translate(-left, -top);
	    float scale = width / view.getWidth();
	    canvas.scale(scale, scale, left, top);
	    view.draw(canvas);
	    canvas.restoreToCount(status);
	    Paint alphaPaint = new Paint();
	    alphaPaint.setColor(Color.TRANSPARENT);
	    canvas.drawRect(0f, 0f, 1f, height, alphaPaint);
	    canvas.drawRect(width - 1f, 0f, width, height, alphaPaint);
	    canvas.drawRect(0f, 0f, width, 1f, alphaPaint);
	    canvas.drawRect(0f, height - 1f, width, height, alphaPaint);
	    canvas.setBitmap(null);
	    return bitmap;
	}


public static String screenshot(Context context, Bitmap bitmap, String name) {
        if (bitmap == null) {
            return null;
        }

        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        if (name == null || name.trim().isEmpty()) {
            name = String.valueOf(System.currentTimeMillis());
        }
        name = name.trim();

        int count = 0;
        File file = new File(dir, name + ".png");
        while (file.exists()) {
            count++;
            file = new File(dir, name + "." + count + ".png");
        }

        try {
            FileOutputStream stream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            stream.flush();
            stream.close();
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
            return file.getAbsolutePath();
        } catch (Exception e) {
            return null;
        }
    }


Android Webview 保存为图片

标签:

原文地址:http://blog.csdn.net/tanranran/article/details/46043987

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!