首页 > 代码精文 > Android > android截图工具类
2016
12-29

android截图工具类

public class ScreenShotHelper {

	/**
	 * 保存View的截图到文件
	 * 
	 * @param bmp
	 * @param path
	 *            eg: "/mnt/sdcard/"
	 * @param name
	 *            eg: "abc.png"
	 * @param quality
	 *            质量等级 0~100
	 * @return
	 */
	public static boolean saveViewAsPNG(View v, String path, int quality) {

		boolean ret = false;
		v.setDrawingCacheEnabled(true);
		Bitmap bmp = v.getDrawingCache();
		if (bmp == null) { // 实在截取不到view就截全屏吧
			v.setDrawingCacheEnabled(false);
			v = v.getRootView();
			v.setDrawingCacheEnabled(true);
			bmp = v.getDrawingCache();
		}
		if (bmp != null) {
			FileOutputStream fOut = null;
			try {
				File f = new File(path);
				File dir = f.getParentFile();
				if (!dir.exists()) {
					dir.mkdirs();
				}
				f.createNewFile();
				fOut = new FileOutputStream(f);
				bmp.compress(Bitmap.CompressFormat.PNG, quality, fOut);
				fOut.flush();
				ret = true;
			} catch (FileNotFoundException e) {
				// createNewFile failed
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (fOut != null) {
					try {
						fOut.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		v.setDrawingCacheEnabled(false);

		return ret;
	}
}

 

最后编辑:
作者:brain952091926
初级 iOS Developer
捐 赠如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!

留下一个回复