Android以當前Activity為基準進行截屏,androidactivity

來源:互聯網
上載者:User

Android以當前Activity為基準進行截屏,androidactivity
概述:

    首先要知道在Android中截取圖片大的方面可以分成兩個方向,一個是走底層一點,一個是走上層。因為樓主底層代碼比較弱,目前也只是停留在a+b的層面。所以,這篇部落格只是在應用程式層上對螢幕進行一個截取。注意,上面討論的兩個方法與遊戲中是兩個概念,遊戲中對螢幕的截取可以理解成一種假象。什麼樣的一種假象呢?沒有截屏!因為玩遊戲的時候,一般是全屏,這個時候只要儲存記憶體中已經儲存了的映像即可。

    對於應用程式層面的,它是基於Activity的。這裡只是說是基於Activity,不是說一定是要由Activity來。那這句話不是矛盾了嗎?要怎麼理解呢?例如,我現在想要截一張圖,那我總得有一個的內容吧。就好像說我想把當前啟動並執行程式給截個圖,那麼當前位於螢幕頂層的Activity就是這個內容了。這個我想要截一張圖中的我則可以是Activity,也可以是Service,也可以是廣播。


類代碼:

下面大家可以看看已經封裝好了的類的代碼,如下:

public class ScreenShot {// 擷取指定Activity的截屏,儲存到png檔案private static Bitmap takeScreenShot(Activity activity) {// View是你需要的ViewView view = activity.getWindow().getDecorView();view.setDrawingCacheEnabled(true);view.buildDrawingCache();Bitmap bitmap = view.getDrawingCache();// 擷取狀態列高度Rect frame = new Rect();activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);int statusBarHeight = frame.top;System.out.println(statusBarHeight);// 擷取螢幕長和高int width = activity.getWindowManager().getDefaultDisplay().getWidth();int height = activity.getWindowManager().getDefaultDisplay().getHeight();// 去掉標題列Bitmap b = Bitmap.createBitmap(bitmap, 0, statusBarHeight, width, height - statusBarHeight);view.destroyDrawingCache();return b;}// 儲存到sdcardprivate static void savePic(Bitmap b, String strFileName) {FileOutputStream fos = null;try {fos = new FileOutputStream(strFileName);if (null != fos) {b.compress(Bitmap.CompressFormat.PNG, 90, fos);fos.flush();fos.close();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public static void shoot(Activity activity) {ScreenShot.savePic(ScreenShot.takeScreenShot(activity), "sdcard/apic/image" + System.currentTimeMillis() + ".png");}}

上面的注釋也留得相對詳細,這裡就不做過多說明了。說了也只是充字數,不必了。


使用示範:

ScreenShot.shoot(MainActivity.this);

運行圖例:


<後續再更新另一種方法。。。>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.