如何通过代码而不是程序来截取手机屏幕的选定区域的截图?


当前回答

如果你想捕捉一个视图的截图,使用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")

我已经回答过一个类似的问题。