使用Bitmap createBitmap遇到的問題,bitmapcreatebitmap
public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height,
Matrix m, boolean filter)
在使用這個方法進行圖片縮放裁剪時,x,y的意思理解錯誤,導致結果不是我想要的效果。
這裡的x,y的值在原始碼中有說明,但是我沒有注意,應該是擷取源bitmap中的座標。
還有x+width要小於或等於source.getWidth(),y+height要小於或等於source.getHeight()
/** * 按寬/高縮放圖片到指定大小並進行裁剪得到中間部分圖片 * * @param bitmap 源bitmap * @param w 縮放後指定的寬度 * @param h 縮放後指定的高度 * @return 縮放後的中間部分圖片 */ public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float scaleWidht, scaleHeight, x, y; Bitmap newbmp; Matrix matrix = new Matrix(); if (width > height) { scaleWidht = ((float) h / height); scaleHeight = ((float) h / height); x = (width - w * height / h) / 2;//擷取bitmap源檔案中x做表需要位移的像數大小 y = 0; } else if (width < height) { scaleWidht = ((float) w / width); scaleHeight = ((float) w / width); x = 0; y = (height - h * width / w) / 2;//擷取bitmap源檔案中y做表需要位移的像數大小 } else { scaleWidht = ((float) w / width); scaleHeight = ((float) w / width); x = 0; y = 0; } matrix.postScale(scaleWidht, scaleHeight); try { newbmp = Bitmap.createBitmap(bitmap, (int) x, (int) y, (int) (width - x), (int) (height - y), matrix, true);//createBitmap()方法中定義的參數x+width要小於或等於bitmap.getWidth(),y+height要小於或等於bitmap.getHeight() } catch (Exception e) { e.printStackTrace(); return null; } return newbmp; }