一、原始需求
1.將兩張圖片(Bitmap)進行融合疊加,得到一個半透明的蒙版覆蓋再圖片上,而被疊加的圖片必須和蒙版大小一樣。其實這需求是比較簡單的,有很多方法都可以實現。之所以寫一寫是因為這里面有機型兼容的坑。
而且網上幾乎沒有提到過這個坑。ps:可能機型太少沒測試到。
二、使用到的工具
1.不成熟的方案:ps:不能兼容特殊機型,如一加手機,三星手機等。這個中方案不管是在小米、華為、oppo、vivo上都沒有多大的毛病,但是如上的兩種特殊的機型不行(或許還有其他的不過測試部沒那么多測試機)
public static Bitmap zoomImg(Bitmap bm, int newWidth ,int newHeight){ // 獲得圖片的寬高 int width = bm.getWidth(); int height = bm.getHeight(); // 計算縮放比例 float scaleWidth = 1.0f*newWidth / width; float scaleHeight = 1.0f*newHeight / height; // 取得想要縮放的matrix參數 Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); // 得到新的圖片 Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true); // Bitmap newbm = Bitmap.createScaledBitmap(bm,newWidth,newHeight,true); return newbm; }
2.相對成熟的方案:ps:可兼容絕大多數的機型,包括一些特殊的機型,如一加手機、三星手機。
private static Bitmap zoomImg2(Bitmap bm, int targetWidth, int targetHeight) { int srcWidth = bm.getWidth(); int srcHeight = bm.getHeight(); float widthScale = targetWidth * 1.0f / srcWidth; float heightScale = targetHeight * 1.0f / srcHeight; Matrix matrix = new Matrix(); matrix.postScale(widthScale, heightScale, 0, 0); // 如需要可自行設置 Bitmap.Config.RGB_8888 等等 Bitmap bmpRet = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bmpRet); Paint paint = new Paint(); canvas.drawBitmap(bm, matrix, paint); return bmpRet; }
三、總結
強烈建議用第二種方案,因為第二種方案是最穩健的,所有的東西都需要自行實現,其Api可以兼容到4.x的版本,非常穩定。