如何在Android上截屏?

时间:2019-03-16 17:24:54

标签: java android screenshot

我正在尝试使用下面的代码截屏,我点击了takeScreenshot()上的按钮,但没有任何反应。

private void takeScreenshot() {
    Date now = new Date();
    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

    try {
        // image naming and path  to include sd card  appending name you choose for file
        String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

        // create bitmap screen capture
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        File imageFile = new File(mPath);

        FileOutputStream outputStream = new FileOutputStream(imageFile);
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        outputStream.flush();
        outputStream.close();


    } catch (Throwable e) {
        // Several error may come out with file handling or DOM
        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:1)

尝试一下,首先创建类:

public class TakeScreenshot {
public static Bitmap takescreenshot(View view) {
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache(true);
    Bitmap b = Bitmap.createBitmap(view.getDrawingCache());
    view.setDrawingCacheEnabled(false);
    return b;
}
public static Bitmap takescreenshotofview(View view) {
    return takescreenshot(view.getRootView());
}}

在MainActivity中:

public void onClick(View view) {
            Bitmap b = TakeScreenshot.takescreenshotview(imageView);
            imageView.setImageBitmap(b);
        }