編輯:關於 Android 程式設計
Bitmap 是 Android 圖片處理的核心,也是記憶體問題的高發區。這篇把日常開發最常用到的操作整理成一份備忘錄,從讀取、縮放、裁切到特效,並附上省記憶體的關鍵參數說明。
Resources res = getResources();
Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.pic);
// 或者從 Drawable 轉
Bitmap bmp2 = ((BitmapDrawable) getResources().getDrawable(R.drawable.show)).getBitmap();
若在意記憶體,可以透過 Options 指定較省的色彩配置:
/** 以最省記憶體的方式讀取本地資源圖片 */
public Bitmap readBitMap(int resId) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565; // 16bit,不帶 alpha
opt.inPurgeable = true;
opt.inInputShareable = true;
InputStream is = getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is, null, opt);
}
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE
? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
直接 decode 一張 4000×3000 的相片足以引發 OOM。正確做法是先只讀取尺寸邊界,算出縮放比,再真正解碼:
public static Bitmap readBitmapAutoSize(String filePath, int outWidth, int outHeight) {
FileInputStream fs = null;
BufferedInputStream bs = null;
try {
fs = new FileInputStream(filePath);
bs = new BufferedInputStream(fs);
BitmapFactory.Options options = setBitmapOption(filePath, outWidth, outHeight);
return BitmapFactory.decodeStream(bs, null, options);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bs.close();
fs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private static BitmapFactory.Options setBitmapOption(String file, int width, int height) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true; // 只量測尺寸,不真正配置像素記憶體
BitmapFactory.decodeFile(file, opt);
int outWidth = opt.outWidth;
int outHeight = opt.outHeight;
opt.inDither = false;
opt.inPreferredConfig = Bitmap.Config.RGB_565; // 16bit 顏色,預設的 ARGB_8888 用不上
opt.inSampleSize = 1; // 1 為原比例,2 為四分之一
if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0) {
opt.inSampleSize = (outWidth / width + outHeight / height) / 2;
}
opt.inJustDecodeBounds = false; // 最後把旗標復原
return opt;
}
inJustDecodeBounds = true 是這套技巧的精髓:它讓 BitmapFactory 只解析檔案標頭取得寬高,不分配像素緩衝區,代價幾乎可以忽略。
/** 圖片透明度處理,number 為 0~100 */
public static Bitmap setAlpha(Bitmap sourceImg, int number) {
int[] argb = new int[sourceImg.getWidth() * sourceImg.getHeight()];
sourceImg.getPixels(argb, 0, sourceImg.getWidth(), 0, 0,
sourceImg.getWidth(), sourceImg.getHeight());
number = number * 255 / 100;
for (int i = 0; i < argb.length; i++) {
argb[i] = (number << 24) | (argb[i] & 0x00FFFFFF); // 只改最高 8 位 alpha
}
return Bitmap.createBitmap(argb, sourceImg.getWidth(),
sourceImg.getHeight(), Config.ARGB_8888);
}
做法是在新 Bitmap 上先畫圓角矩形,再用 PorterDuffXfermode 把原圖「裁」進去:
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, w, h);
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, 10, 10, paint); // 圓角平滑度 10
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
實務上還常搭配「先放大再裁圓角」的版本,避免小圖被填進大框時出現模糊:
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int width, int height) {
int w = bitmap.getWidth(), h = bitmap.getHeight();
// 若原圖小於目標尺寸,先等比放大
if (w < width || h < height) {
Matrix matrix = new Matrix();
matrix.postScale((float) width / w, (float) height / h);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
}
Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Paint paint = new Paint();
Rect rect = new Rect(0, 0, width, height);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(0xff424242);
canvas.drawRoundRect(new RectF(rect), 10, 10, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
// 裁切部分區域
mBitmap = Bitmap.createBitmap(bmp, 100, 100, 120, 120);
// 縮放到指定尺寸
Bitmap scaled = Bitmap.createScaledBitmap(bmp, mScreenWidth, mScreenHeight, true);
但每次呼叫 createBitmap 都會配置新記憶體,並非最佳選擇。更省的做法是繪製時直接縮放或裁切:
// 把 mBitmap 縮放後繪製到 (0,0)-(200,200) 區域
canvas.drawBitmap(mBitmap, null, new Rect(0, 0, 200, 200), null);
// 第二個參數是來源 Rect:把 (100,100)-(300,300) 取出,
// 自動縮放後畫到 (100,100)-(200,200)
canvas.drawBitmap(mBitmap,
new Rect(100, 100, 300, 300),
new Rect(100, 100, 200, 200), null);
用 Matrix 做縮放也是常見寫法:
public Bitmap zoomImage(Bitmap bgimage, int newWidth, int newHeight) {
int width = bgimage.getWidth();
int height = bgimage.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(((float) newWidth) / width, ((float) newHeight) / height);
return Bitmap.createBitmap(bgimage, 0, 0, width, height, matrix, true);
}
/** 將大圖平均分割為 N 行 N 列 */
public final void cuteImage(Canvas g, Paint paint, Bitmap imgBit,
int x, int y, int w, int h, int line, int row) {
g.clipRect(x, y, x + w, h + y);
g.drawBitmap(imgBit, x - line * w, y - row * h, paint);
g.restore();
}
遊戲裡常用来美化文字:先在四個偏移方向畫背景色,再於中心畫前景色。
public void drawText(String strMsg, Canvas g, Paint paint,
int setx, int sety, int fg, int bg) {
paint.setColor(bg);
g.drawText(strMsg, setx + 1, sety, paint);
g.drawText(strMsg, setx, sety - 1, paint);
g.drawText(strMsg, setx, sety + 1, paint);
g.drawText(strMsg, setx - 1, sety, paint);
paint.setColor(fg);
g.drawText(strMsg, setx, sety, paint);
g.restore();
}
// 旋轉 90 度
img = BitmapFactory.decodeResource(getResources(), R.drawable.slogo);
Matrix matrix = new Matrix();
matrix.postRotate(90);
int width = img.getWidth(), height = img.getHeight();
r_img = Bitmap.createBitmap(img, 0, 0, width, height, matrix, true);
// 產生帶漸層淡出的倒影
public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
final int reflectionGap = 4;
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.preScale(1, -1); // 垂直翻轉
Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,
width, height / 2, matrix, false);
Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
height + height / 2, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmapWithReflection);
canvas.drawBitmap(bitmap, 0, 0, null);
Paint defaultPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);
canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
// 用 LinearGradient + DST_IN 讓倒影由上而下淡出
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap,
0x70ffffff, 0x00ffffff, TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
canvas.drawRect(0, height, width,
bitmapWithReflection.getHeight() + reflectionGap, paint);
return bitmapWithReflection;
}
1. decodeStream 不會自動適配螢幕密度。它直接讀取位元組,無視機器的 dpi 差異,因此同一張圖在不同解析度裝置上會顯示出不同實體大小。解法是明確告訴它目標密度:
BitmapFactory.Options opts = new BitmapFactory.Options();
// 將圖片 DPI 設為當前螢幕的 densityDpi
opts.inTargetDensity = ctx.getResources().getDisplayMetrics().densityDpi;
opts.inScaled = true;
或者更根本地,在 hdpi / mdpi / ldpi 各資料夾中準備對應資源的圖片。
2. Bitmap 是大物件,不用時請主動回收。
if (!bmp.isRecycled()) {
bmp.recycle(); // 釋放像素記憶體
System.gc(); // 提示系統回收(僅供參考,不宜頻繁呼叫)
}
補充兩點現代的實務建議:其一,Android 3.0 之後 Bitmap 的像素資料已改為與 Java 物件分開管理,recycle() 的必要性下降,窮人的重心應放在「一開始就不要載入過大的圖」;其二,專案裡請優先考慮 Glide 或 Coil 這類圖片載入框架,它們已內建 sampling、快取與生命週期管理,能省下絕 Above 大部分手寫 Bitmap 程式所帶來的 OOM 風險。
用 Google ZXing 打造 Android 二維碼/條形碼掃描與生成功能
一、二維碼與條形碼的工作原理 如今幾乎每款應用都具備掃碼能力。還記得微信剛推出二維碼掃碼時的那種驚艷——一張簡單的圖片,就能完成添加好友、分享名片等操作。本文就重點聊聊
adb bugreport thoroughly 解析:從一行指令到 dumpstate 源碼全通
一、bugreport 是什麼? 一個成熟的行動作業系統,除了功能要完整,還得讓開發者能把問題查清楚。Android 在這件事上做得相當徹底:只要系統或 App 在真机上
Android 日期與時間選擇器實作:TimePickerDialog 與 DatePickerDialog 完整指南
前言 大部分 Android 入門教學都不會提到怎麼讓使用者「選」時間,於是初學者遇到需求時往往不知所措。難不成要讓使用者自己打字輸入日期?先不說體驗很差,光是處理五花八
apktool 反編譯與 Eclipse 多渠道打包實作
在 Android 開發與測試流程中,有時需要對 APK 進行反編譯、重新打包,或針對不同管道產生多個安裝包。本文以 apktool 與 jarsigner 為核心,說明