activity view 截圖

核心

view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
view.destroyDrawingCache(); 

sample from http://my.oschina.net/u/242041/blog/212755

public void screenShot(View view, String fileName) throws Exception {
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        //上面2行必須加入,如果不加如view.getDrawingCache()返回null
        Bitmap bitmap = view.getDrawingCache();
        FileOutputStream fos = null;
        try {
            //判斷sd卡是否存在 
            boolean sdCardExist = Environment.getExternalStorageState() 
                    .equals(android.os.Environment.MEDIA_MOUNTED); 
            if(sdCardExist){
                //獲取sdcard的根目錄
                String sdPath = Environment.getExternalStorageDirectory().getPath();

                //創建程序自己創建的文件夾
                File tempFile= new File(sdPath+File.separator +fileName);
                if(!tempFile.exists()){
                    tempFile.mkdirs();
                }
                //創建圖片文件
                File file = new File(sdPath + File.separator+fileName+File.separator+ "screen" + ".png");
                if(!file.exists()){
                   file.createNewFile();
                }

                image.setImageBitmap(bitmap);
                fos = new FileOutputStream(file);
                if (fos != null) {

                    bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
                    fos.close();
                }
            }


        } catch (Exception e) {
            Log.e(TAG, "cause for "+e.getMessage());
        }

// view.destroyDrawingCache(); 最後應該還要釋放掉。 
//
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章