需求: 截屏
参考 : Android开发:截屏 screenshot 功能小结
方法1.使用shell 命令 screencap -p test.png
方法2.java代码实现
import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Rect; import android.util.Log; import android.view.View; import android.view.Window; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class ScreenShotUtil { /** * 截图 * * @param activity 截取activity 所在的页面的截图,即使退到后台也是截取这个activity * @param strFileName 文件全路径:例如 "/sdcard/screen_shot_20160424.jpg" */ public static void shot(Activity activity, String strFileName) { Bitmap takeShot = takeShot(activity); savePic(takeShot, strFileName); } private static Bitmap takeShot(Activity activity) { // 获取windows中最顶层的view View view = activity.getWindow().getDecorView(); // 允许当前窗口保存缓存信息 view.setDrawingCacheEnabled(true); view.buildDrawingCache(); //状态栏高度 Rect outRect = new Rect(); view.getWindowVisibleDisplayFrame(outRect); int statusBarHeight = outRect.top; //状态栏+标题栏目的高度 statusBarHeight = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); //屏幕宽高 int height = activity.getWindowManager().getDefaultDisplay().getHeight(); int width = activity.getWindowManager().getDefaultDisplay().getWidth(); Bitmap b = Bitmap.createBitmap(view.getDrawingCache(), 0, statusBarHeight, width, height - statusBarHeight); // 销毁缓存信息 view.destroyDrawingCache(); return b; } // 保存到sdcard private static void savePic(Bitmap b, String strFileName) { FileOutputStream fos = null; try { Log.i("TAG", "start savePic"); fos = new FileOutputStream(strFileName); Log.i("TAG", "strFileName = " + strFileName); if (null != fos) { // 第一参数是图片格式,第二个是图片质量,第三个是输出流 b.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); fos.close(); Log.i("TAG", "save pic"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
时间: 2024-11-08 01:58:28