編輯:關於 Android 程式設計
「分享這一刻」是許多 app 都會有的功能,而要在使用者不按下硬體鍵的前提下取得畫面,最簡單的途徑就是 View.setDrawingCacheEnabled()。原理是讓 View 把當前內容繪製到一塊記憶體快取中,我們再把這塊快取取出來轉成 Bitmap。
package net.canking.shottest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.view.View;
public class ScreenShot {
private static Bitmap takeScreenShot(Activity activity) {
// 指定要截圖的 View,這裡取整個視窗
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
// 取得狀態列高度,準備裁掉
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
// 取得螢幕寬高
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay().getHeight();
// 去掉狀態列後裁切
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return b;
}
private static void savePic(Bitmap b, File filePath) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filePath);
if (null != fos) {
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void shoot(Activity a, File filePath) {
if (filePath == null) return;
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();
}
ScreenShot.savePic(ScreenShot.takeScreenShot(a), filePath);
}
}
為什麼要裁狀態列:getDecorView() 拿到的是包含系統狀態列的整個視窗,若不需要狀態列,就要透過 getWindowVisibleDisplayFrame() 取得狀態列高度再裁切。相對地,若想連標題列一起去掉,就改用 content 這個子 View 當截圖來源。
一定要 destroyDrawingCache:這塊快取佔用可觀的記憶體,用完不釋放會直接推向 OOM。範例中已正確呼叫。
硬體加速的限制:在開啟硬體加速的機型上,某些自繪內容(例如部分 OpenGL 渲染)不會被 DrawingCache 正確擷取。遇到這種情況需要改用 PixelCopy(API 24 以上)或 MediaProjection 進行真正的螢幕擷取。
權限與儲存位置:Android 10 之後不建議直接寫外部儲存空間,應改用 MediaStore 或 app 專用目錄;同時記得在 manifest 中依目標 SDK 版本宣告對應權限。
Android 實戰:打造屬於你自己的數據庫操作類
一、概述 做安卓的同學都知道,SDK 已經為我們準備了 SQLiteOpenHelper 類來創建和管理 SQLite 數據庫,只要寫個子類繼承它,就能方便地完成數據庫的
LitePal建立資料表關聯:一對一、多對一與多對多
LitePal能讓開發者以物件導向方式描述資料表關聯,不必手動處理複雜SQL。三種關聯一對一通常以單一物件引用表示;多對一會在「多」的一方加入集合;多對多則需要中間表,L
Android MVP 架構入門:用一個登入頁把 View、Model、Presenter 拆乾淨
說來慚愧,MVP 這個模式在 Android 圈子已經流行一兩年了,我卻直到現在才真正動手實作一次。閒話少說,直接開始。 一、為什麼從 MVC 走到 MVP 記得找第一份
自訂 ScrollView 實作背景圖片伸縮動效:完整思路與程式碼
用過多米音樂的朋友都知道,它的某個 UI 可以上下滑動——作用嘛,無聊時可以劃劃解解悶。這種細節往往被形容成一種「情懷」,不過叫「情味」或許更貼切。如今行動網際網路發