Android 实现截屏功能
主要代码如下:
private void getScreen(View view, String filePath) { try { Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Config.ARGB_8888); Canvas canvas=new Canvas(); canvas.setBitmap(bitmap); view.draw(canvas); FileOutputStream outputStream=new FileOutputStream(filePath); bitmap.compress(CompressFormat.JPEG, 100, outputStream); } catch (Exception e) { e.printStackTrace(); } }
//判断sdCard是否存在 if(sdCardStat.equals(Environment.MEDIA_MOUNTED)) { //sdCard卡路径 File sdSardDir=Environment.getExternalStorageDirectory(); getScreen((View)getWindow().getDecorView(),sdSardDir+"/test1.png"); Toast.makeText(MainActivity.this, "截图成功", Toast.LENGTH_LONG).show(); }else { Toast.makeText(MainActivity.this,"sdcard不可用", Toast.LENGTH_LONG).show(); }
最后在AndroidManifest中添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
截图成功之后会在sdcard下看到test1.png图片,
本人在真机上测试可行,没有在模拟器上测试。