先上效果图
qq效果的图片是在github上找的项目 https://github.com/kongnanlive/android-combination-avatar
仿微信群头像是自己鼓捣出来的
先贴一下主要代码
private static Bitmap createTogetherBit(Bitmap[] paramList,
final Context context) {
if (paramList.length < 1 && paramList.length > 9) {
return null;
}
// 先取一个获取宽和高
Bitmap tempBitmap = (Bitmap) paramList[0];
if (tempBitmap == null) {
return null;
}
// 画布的宽
int tempWidth = tempBitmap.getWidth();
// 画布的高
int tempHeight = tempBitmap.getHeight();
// 创建一个空格的bitmap
Bitmap canvasBitmap = Bitmap.createBitmap(tempWidth, tempHeight,
Bitmap.Config.ARGB_8888);
// 头像的数量
int bitmapCount = paramList.length;
Canvas localCanvas = new Canvas(canvasBitmap);
localCanvas.drawColor(Color.GRAY);
int colum = 0;
if (bitmapCount > 0 && bitmapCount < 5) {
colum = 2;
} else if (bitmapCount > 4 && bitmapCount < 10) {
colum = 3;
}
float scale = 1.0F / colum;
// 根据列数缩小
Bitmap scaledBitmap = scaleBitmap(scale, tempBitmap);
if (PADDING > 0) {
PADDING = dip2px(context, PADDING);
// 如果有内边距 再次缩小
float paddingScale = (float) (tempWidth - (colum + 1) * PADDING)
/ colum / scaledBitmap.getWidth();
scaledBitmap = scaleBitmap(paddingScale, scaledBitmap);
scale = scale * paddingScale;
}
// 第一行的 头像个数
int topRowCount = bitmapCount % colum;
// 满行的行数
int rowCount = bitmapCount / colum;
if (topRowCount > 0) {
// 如果第一行头像个数大于零 行数加1
rowCount++;
} else if (topRowCount == 0) {
// 6 或者 9 第一行头像个数和列数一致
topRowCount = colum;
}
// 缩小后头像的宽
int scaledWidth = scaledBitmap.getWidth();
// 缩小后头像的高
int scaledHeight = scaledBitmap.getHeight();
// 第一个头像与画布顶部的距离
int firstTop = ((tempHeight - (rowCount * scaledHeight + (rowCount + 1)
* PADDING)) / 2)
+ PADDING;
// 第一个头像与画布左部的距离
int firstLeft = ((tempWidth - (topRowCount * scaledWidth + (topRowCount + 1)
* PADDING)) / 2)
+ PADDING;
for (int i = 0; i < paramList.length; i++) {
if (i == 9) {// 达到上限 停止
break;
}
// 按照最终压缩比例压缩
Bitmap bit = scaleBitmap(scale, (Bitmap) paramList[i]);
if (ROUNDPX > 0) {
// 圆角化
bit = GetRoundedCornerBitmap(bit);
}
localCanvas.drawBitmap(bit, firstLeft, firstTop, null);
firstLeft += (scaledWidth + PADDING);
if (i == topRowCount - 1 | tempWidth - firstLeft < scaledWidth) {
firstTop += (scaledHeight + PADDING);
firstLeft = PADDING;
}
bit.recycle();
}
// 重置padding
PADDING = 2;
localCanvas.save(Canvas.ALL_SAVE_FLAG);
localCanvas.restore();
return canvasBitmap;
}
思路就是里面小头像的缩放大小是根据列数多少决定的,所以根据列数算出缩放的比例,然后就根据总个数一行一行的向画布中画小头像,中间加上了padding,更灵活一些,方法可能比较low,效果还是可以的。
demo下载地址