一、原始需求
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的版本,非常稳定。