編輯:關於 Android 程式設計
很多時候我們想把整個界面的內容分享出去,但內容太長、超出了屏幕範圍,普通截屏就不管用了。這時候可以根據 ScrollView 裡子 View 的實際高度來「畫」出一張長圖。
不走「截屏 + 拼接」的路子,而是直接讓 ScrollView draw() 到一張足夠大的 Bitmap 畫布上。這樣一次性得到完整內容,不必處理滾動與拼接的接縫問題。
/**
* 截取 scrollView 的完整內容
*/
public static Bitmap getBitmapByView(ScrollView scrollView) {
int h = 0;
Bitmap bitmap = null;
// 累加所有子 View 的實際高度
for (int i = 0; i < scrollView.getChildCount(); i++) {
h += scrollView.getChildAt(i).getHeight();
// 鋪白底,避免透明區域在深色模式下發黑
scrollView.getChildAt(i).setBackgroundColor(Color.parseColor("#ffffff"));
}
// 創建對應尺寸的 bitmap
bitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.RGB_565);
final Canvas canvas = new Canvas(bitmap);
scrollView.draw(canvas);
return bitmap;
}
/**
* 質量壓縮,控制體積
*/
public static Bitmap compressImage(Bitmap image) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 100;
// 循環判斷:超過 100KB 就繼續壓
while (baos.toByteArray().length / 1024 > 100) {
baos.reset();
image.compress(Bitmap.CompressFormat.JPEG, options, baos);
options -= 10; // 每次遞減 10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
return BitmapFactory.decodeStream(isBm, null, null);
}
/**
* 保存到 /sdcard/image
*/
public static String savePic(Bitmap b) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US);
File outfile = new File("/sdcard/image");
if (!outfile.isDirectory()) {
try {
outfile.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
String fname = outfile + "/" + sdf.format(new Date()) + ".png";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fname);
if (null != fos) {
b.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fname;
}
String fname = ScreenShot.savePic(ScreenShot.getBitmapByView(scrollView));
這樣寫有時會因為截出的圖太長太大而崩潰。兩個必須注意的地方:
String fname = ScreenShot.savePic(
ScreenShot.compressImage(ScreenShot.getBitmapByView(scrollView)));
ViewTreeObserver 配合逐步滾動錄製。WRITE_EXTERNAL_STORAGE,Android 7.0 之後建議改用 FileProvider 或 App 私有目錄,避免 FileUriExposedException。
Android Canvas 繪圖 API 筆記:從基本圖形到自定義 View
在 Android 自定義 View 中,Canvas 是繪製內容的畫布,而 Paint 則像畫筆,決定顏色、線寬、樣式與抗鋸齒等效果。View 的 onDraw 回呼會
Android 自繪動畫實戰與性能優化——以 Tencent OS 錄音機波形動效為例
一、先把繪制原理說清楚 Android 的圖形繪製主要建立在 View 之上。每個 View 的呈現都要走一遍 onMeasure、onLayout、onDraw 三步曲
Android Intent 與 IntentFilter 詳解:Uri 解析與 Activity 匹配規則
當你希望自己的 Activity 能被其他應用打開,或者想在 WebView、第三方 App 中呼叫自己的頁面時,IntentFilter 就派上用場了。它負責「過濾」出
Android Drawable 詳解:從 BitmapDrawable 到 ClipDrawable
Drawable 是 Android 中非常常見的資源類型。它可以是一張圖片,也可以是通過 XML 定義的形狀、漸變、層疊或裁剪效果。掌握 Drawable,可以讓界面背