需求
照片排列公式:照片数x,开根号,向上取整是列数y;x/y,向上取整是行数z;y*z-x,是需补齐的照片数;列数有1-10的十种情况;例如照片44张,则显示7行7列,最后一行最后5张自动重复开始的5张;
效果图
代码
/**
* 多张图片拼接宫格
*
* @param squareSideLength 最终生成正方形的边长
* @param margin 每个item的间距
* @param
* @return
*/
public static Bitmap compositeBitmap(int squareSideLength, int margin, Bitmap... bitmaps) {
//图片个数
int count = bitmaps.length;
//行数
int row = (int) Math.ceil(Math.sqrt(count));
//列数
int col = row;
//item边长
int itemSide = (squareSideLength - (col - 1) * margin) / col;
Log.d("wqs", "-->总高度=" + squareSideLength + " 间距=" + margin);
Log.d("wqs", "-->行数=" + row + " 列数=" + col);
Log.d("wqs", "-->item的高度和宽度=" + itemSide);
Bitmap result = Bitmap.createBitmap(squareSideLength, squareSideLength, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int index = i * row + j < count ? i * row + j : (i * row + j) % count;
int left = margin * j + itemSide * j;
int top = margin * i + itemSide * i;
Log.d("wqs", "-->第" + i + "行 第" + j + "列:" + "left=" + left + " top=" + top);
Bitmap sourceBitmp = bitmaps[index];
Bitmap itemBitmap = Bitmap.createBitmap(sourceBitmp, 0, 0,
itemSide < sourceBitmp.getWidth() ? itemSide : sourceBitmp.getWidth(),
itemSide < sourceBitmp.getHeight() ? itemSide : sourceBitmp.getHeight());
canvas.drawBitmap(itemBitmap, left, top, null);
}
}
return result;
}