android – 截图

我正在开发一个在设备中截取屏幕截图的应用程序.在这个应用程序中,我们可以在屏幕上绘制任何东西.为此,我使用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(),Bitmap.Config.ARGB_8888);

我的应用程序关闭时出现以下异常:

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

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

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

解决方法

你可以这样做,

给你的主要布局&在屏幕上显示内容之后,在一些监听器上写下面的代码,说按钮单击或菜单项或任何这样的监听器(确保在布局显示调用这些行,否则将给出一个空白屏幕).

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

方法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,ostream);
            ostream.close();
        } 
        catch (Exception e) 
        {
            e.printstacktrace();
        }
    }

也不要添加向SDCard写入文件的权限.

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

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...