android - 截图

标签 android path screenshot paint android-canvas

我正在开发一个用于在设备中截取屏幕截图的应用程序。在这个应用程序中,我们可以在屏幕上绘制任何东西。为此,我使用 Canvas、Paint 和 Path 来执行此操作。

我正在使用此代码截取屏幕截图:

        public void saveScreenshot() 
    {
        if (ensureSDCardAccess()) 
        {
            Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            onDraw(canvas);
            File file = new File(mScreenshotPath + "/" + System.currentTimeMillis() + ".jpg");
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.close();
            } catch (FileNotFoundException e) {
                Log.e("Panel", "FileNotFoundException", e);
            } catch (IOException e) {
                Log.e("Panel", "IOEception", e);
            }
        }
    }

    /**
     * Helper method to ensure that the given path exists.
     * TODO: check external storage state
     */
    private boolean ensureSDCardAccess() {
        File file = new File(mScreenshotPath);
        if (file.exists()) {
            return true;
        } else if (file.mkdirs()) {
            return true;
        }
        return false;
    }

但是,当运行以下行时:

Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);

我的应用程序因以下异常而关闭:

11-28 15:05:46.291: E/AndroidRuntime(8209): java.lang.IllegalArgumentException: width and height must be > 0

如果我改变高度和宽度,屏幕截图会被截取,但它是空的:

Empty

为什么会这样?我做错了什么?

最佳答案

你可以这样做,

为您的主布局提供 id 并在屏幕上显示内容后,在某些监听器上写下以下代码,例如按钮单击或菜单项或任何此类监听器(确保在布局显示后调用这些行,否则它将给出一个空白屏幕)。

        View content = findViewById(R.id.myLayout);
        content.setDrawingCacheEnabled(true);
        getScreen(content);

方法获取屏幕(内容)

private void getScreen(View content)
    {
        Bitmap bitmap = content.getDrawingCache();
        File file = new File("/sdcard/test.png");
        try 
        {
            file.createNewFile();
            FileOutputStream ostream = new FileOutputStream(file);
            bitmap.compress(CompressFormat.PNG, 100, ostream);
            ostream.close();
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }

也不要添加写文件到SDCard的权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
                                                               </uses-permission>

关于android - 截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8294110/

相关文章:

.net - 如何检查路径中的非法字符?

python - 在Python中获取调用者的相对路径

C++通过Windows搜索路径查找可执行文件

linux - 在 perl 中截图

android - Material UI Layout 按角线划分

java - 如何在android中的另一个 View 上创建 float View

java - 致命异常 : Main Android Eclipse

Android Activity绘制完成

ios - 如何截取单个 View 对象而不是整个屏幕的屏幕截图?

android - Long TextViews 在 LinearLayout 中将元素推离屏幕