我有两张存储在安卓SD卡上的本地图片,想要将它们合成一张图片。很难用语言解释,因此我会链接一张图片,以更好地说明我希望如何将前两张图片合并成最后一张。
我有两张存储在安卓SD卡上的本地图片,想要将它们合成一张图片。很难用语言解释,因此我会链接一张图片,以更好地说明我希望如何将前两张图片合并成最后一张。
我通常使用以下函数来自Jon Simon的,将传递的两个位图合并为一个,并获得合并的位图作为输出。
public Bitmap combineImages(Bitmap c, Bitmap s)
{
Bitmap cs = null;
int width, height = 0;
if(c.getWidth() > s.getWidth()) {
width = c.getWidth() + s.getWidth();
height = c.getHeight();
} else {
width = s.getWidth() + s.getWidth();
height = c.getHeight();
}
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, c.getWidth(), 0f, null);
return cs;
}
创建目标位图(Bitmap)
,为其创建一个画布(Canvas)
,使用Canvas.drawBitmap
将每个源位图合成到目标位图中。
最简单的方法可能是在RelativeLayout中使用两个ImageView。您可以在布局中将ImageViews相互叠放。
与Hitesh的回答类似,但具有指定前景图像位置的参数:
public static Bitmap mergeBitmaps(Bitmap bitmapBg, Bitmap bitmapFg, float fgLeftPos, float fgTopPos) {
// Calculate the size of the merged Bitmap
int mergedImageWidth = Math.max(bitmapBg.getWidth(), bitmapFg.getWidth());
int mergedImageHeight = Math.max(bitmapBg.getHeight(), bitmapFg.getHeight());
// Create the return Bitmap (and Canvas to draw on)
Bitmap mergedBitmap = Bitmap.createBitmap(mergedImageWidth, mergedImageHeight, bitmapBg.getConfig());
Canvas mergedBitmapCanvas = new Canvas(mergedBitmap);
// Draw the background image
mergedBitmapCanvas.drawBitmap(bitmapBg, 0f, 0f, null);
//Draw the foreground image
mergedBitmapCanvas.drawBitmap(bitmapFg, fgLeftPos, fgTopPos, null);
return mergedBitmap;
}