public static Bitmap zoomIn(Bitmap bitmap, int maxW, int maxH) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
if (width <= maxW && height <= maxH)
return bitmap;
Matrix matrix = new Matrix(); // 建立操作圖檔用的Matrix對象
float ratio = (float) getRatio(width, height, maxW, maxH);
matrix.postScale(ratio, ratio); // 設定縮放比例
// Bitmap oldbmp = drawable.getBitmap(); // drawable轉換成bitmap
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); // 建立新的bitmap,其内容是對原bitmap的縮放後的圖
return newbmp; // 把bitmap轉換成drawable并傳回
}
private static double getRatio(int srcWidth, int srcHeight, int maxWidth, int maxHeight) {
double ratio = 0.0;
double ratio_w = 0.0;
double ratio_h = 0.0; // 按比例計算縮放後的圖檔大小,maxLength是長或寬允許的最大長度
if (srcWidth <= maxWidth && srcHeight <= maxHeight) {
return 0.0;
}
ratio_w = (double)maxWidth / (double)srcWidth;
ratio_h = (double)maxHeight / (double)srcHeight; if (ratio_w < ratio_h) {
ratio = ratio_w;
} else {
ratio = ratio_h;
} return ratio;
}