两个Bitmap合并为一个
2019-06-04 本文已影响3人
Small_Cake
/**
* 合并两张bitmap为一张
*
* @param background
* @param foreground
* @return Bitmap
*/
public static Bitmap combineBitmap(Bitmap background, Bitmap foreground) {
if (background == null) {
return null;
}
int bgWidth = background.getWidth();
int bgHeight = background.getHeight();
foreground =zoomImg(foreground,200,200);
int fgWidth = foreground.getWidth();
int fgHeight = foreground.getHeight();
Bitmap newmap = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newmap);
canvas.drawBitmap(background, 0, 0, null);
canvas.drawBitmap(foreground, (bgWidth - fgWidth) / 2, (bgHeight - fgHeight) / 2, null);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
return newmap;
}
/**
* 缩放bitmap
* @param bm
* @param newWidth
* @param newHeight
* @return
*/
public static Bitmap zoomImg(Bitmap bm, int newWidth ,int newHeight){
// 获得图片的宽高
int width = bm.getWidth();
int height = bm.getHeight();
// 计算缩放比例
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 取得想要缩放的matrix参数
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 得到新的图片
Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
return newbm;
}