租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

android截屏代码如何写,android 截图命令

发布时间:2023-10-13 19:13:55

android截屏代码如何写

在Android中,可使用以下代码来实现截屏:

private void takeScreenshot() {
// 获得屏幕视图
View view = getWindow().getDecorView().getRootView();
// 创建Bitmap对象并指定大小
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
// 创建Canvas对象,并将Bitmap与其关联
Canvas canvas = new Canvas(bitmap);
// 将屏幕视图绘制到Canvas上
view.draw(canvas);
// 保存截屏图片
try {
// 指定保存路径和文件名
String filePath = Environment.getExternalStorageDirectory() + "/screenshot.png";
File file = new File(filePath);
// 创建文件输出流
FileOutputStream fos = new FileOutputStream(file);
// 将Bitmap对象紧缩为PNG格式,并写入文件输出流
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
// 刷新文件输出流
fos.flush();
// 关闭文件输出流
fos.close();
Toast.makeText(this, "截屏已保存至" + filePath, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}

在调用截屏方法之前,需要添加相应的权限到AndroidManifest.xml文件中:

当调用takeScreenshot()方法时,会将当前屏幕内容保存为PNG格式的图片,并保存到装备的外部存储目录中,同时显示一个Toast提示保存路径。