在開發過程中,經常要用到分享功能,有時需要截取當前螢幕的畫面,一起分享出去。如果當前Activity高度固定,不能滑動,截取螢幕代碼網上到處都是,這裡就不貼出了;如果當前Activity嵌套有可滑動子控制項,如ScrollView或ListView,想要連未顯示的部分一起截下來,前一種方法就行不通了,這裡貼出一段有效代碼:
/** * 截取scrollview的螢幕 * **/ public static Bitmap getBitmapByView(ScrollView scrollView) { int h = 0; Bitmap bitmap = null; // 擷取listView實際高度 for (int i = 0; i < scrollView.getChildCount(); i++) { h += scrollView.getChildAt(i).getHeight(); scrollView.getChildAt(i).setBackgroundResource(R.drawable.bg3); } Log.d(TAG, "實際高度:" + h); Log.d(TAG, " 高度:" + scrollView.getHeight()); // 建立對應大小的bitmap bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(bitmap); scrollView.draw(canvas); // 測試輸出 FileOutputStream out = null; try { out = new FileOutputStream("/sdcard/screen_test.png"); } catch (FileNotFoundException e) { e.printStackTrace(); } try { if (null != out) { bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); } } catch (IOException e) { // TODO: handle exception } return bitmap; }
附Demo:點擊開啟連結