如何通过代码而不是程序来截取手机屏幕的选定区域的截图?
当前回答
如果你想捕捉一个视图的截图,使用View::drawToBitmap扩展函数:
val bitmap = myTargetView.drawToBitmap(/*Optional:*/ Bitmap.Config.ARGB_8888)
只需要确保使用-ktx版本的AndroidX核心库:
implementation("androidx.core:core-ktx:1.6.0")
我已经回答过一个类似的问题。
其他回答
注:仅适用于root phone
编程方式:adb shell /system/bin/screencap -p /sdcard/img.png
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
然后将img.png读取为位图,并按照您的意愿使用。
您可以尝试以下库: http://code.google.com/p/android-screenshot-library/ Android截图库(ASL)允许以编程方式从Android设备捕获屏幕截图,而不需要具有root访问权限。相反,ASL利用了在后台运行的本地服务,每次设备启动时通过Android调试桥(ADB)启动。
参数视图是根布局对象。
public static Bitmap screenShot(View view) {
Bitmap bitmap = null;
if (view.getWidth() > 0 && view.getHeight() > 0) {
bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
}
return bitmap;
}
private void captureScreen() {
View v = getWindow().getDecorView().getRootView();
v.setDrawingCacheEnabled(true);
Bitmap bmp = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
try {
FileOutputStream fos = new FileOutputStream(new File(Environment
.getExternalStorageDirectory().toString(), "SCREEN"
+ System.currentTimeMillis() + ".png"));
bmp.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
在清单中添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
对于支持棉花糖或以上版本,请在onCreate方法中添加以下代码
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},00);
如果你想捕捉一个视图的截图,使用View::drawToBitmap扩展函数:
val bitmap = myTargetView.drawToBitmap(/*Optional:*/ Bitmap.Config.ARGB_8888)
只需要确保使用-ktx版本的AndroidX核心库:
implementation("androidx.core:core-ktx:1.6.0")
我已经回答过一个类似的问题。
推荐文章
- 改变开关的“开”色
- 以编程方式将EditText的输入类型从PASSWORD更改为NORMAL,反之亦然
- 如何在隐藏和查看密码之间切换
- 在Android上调整一个大的位图文件到缩放输出文件
- 如何更改Android版本和代码版本号?
- Android Studio突然无法解析符号
- 应用程序重新启动而不是恢复
- 如何设置整个应用程序在纵向模式?
- Android中文本的阴影效果?
- 以编程方式设置TextView的布局权重
- Android -如何覆盖“后退”按钮,所以它不完成()我的活动?
- 如何从通知点击发送参数到一个活动?
- 导航目标xxx对于这个NavController是未知的
- 使用ConstraintLayout均匀间距的视图
- 文件google-services错误。模块根文件夹中缺少Json。谷歌服务插件没有它就不能正常工作。