微信头像九宫格算法 如:分别计算1-9个头像在九宫格中的位置

分别计算1-9个头像在九宫格中的位置


public static List<ImageCell> createMergeCell(int n, int totalWidth) {
int totalRow = (int) Math.ceil(Math.sqrt(n));
int outline = 5;
int width = ((totalWidth - outline) / totalRow);
int border = width / 20;
if (n == 1) {
return Lists.newArrayList(new ImageCell(border, border, width - 2 * border));
}
int lastAloneNum = n % totalRow;
int totalFullRow = n / totalRow;
int lastRow = totalRow - totalFullRow - 1;

int firstStartX = (totalWidth - lastAloneNum * width) / 2;
int firstStartY = lastRow * width;

int otherSpace = (totalWidth - totalRow * width) / 2;
int yOffset = 0;
if (totalRow != totalFullRow + (lastAloneNum != 0 ? 1 : 0)) {
yOffset = -width / 2;
}
List<ImageCell> imageCells = Lists.newArrayList();
for (int i = 0; i < n; i++) {
int x = 0, y = firstStartY;
if (i < lastAloneNum) {
x = firstStartX + i * width;
} else {
x = (i - lastAloneNum) % totalRow * width;
y = firstStartY + ((i - lastAloneNum) / totalRow + 1) * width;
}
imageCells.add(new ImageCell(x + border + otherSpace, y + border + otherSpace + yOffset, width - 2 * border));
}
return imageCells;
}

@Data
@AllArgsConstructor
static class ImageCell {
int x;
int y;
int width;

}

-------------------n=1---------------------
x:7,y:7,width:131




-------------------n=2---------------------
x:6,y:42,width:66
x:78,y:42,width:66




-------------------n=3---------------------
x:45,y:6,width:66
x:6,y:78,width:66
x:78,y:78,width:66




-------------------n=4---------------------
x:6,y:6,width:66
x:78,y:6,width:66
x:6,y:78,width:66
x:78,y:78,width:66




-------------------n=5---------------------
x:32,y:29,width:44
x:80,y:29,width:44
x:5,y:77,width:44
x:53,y:77,width:44
x:101,y:77,width:44




-------------------n=6---------------------
x:5,y:29,width:44
x:53,y:29,width:44
x:101,y:29,width:44
x:5,y:77,width:44
x:53,y:77,width:44
x:101,y:77,width:44




-------------------n=7---------------------
x:56,y:5,width:44
x:5,y:53,width:44
x:53,y:53,width:44
x:101,y:53,width:44
x:5,y:101,width:44
x:53,y:101,width:44
x:101,y:101,width:44




-------------------n=8---------------------
x:32,y:5,width:44
x:80,y:5,width:44
x:5,y:53,width:44
x:53,y:53,width:44
x:101,y:53,width:44
x:5,y:101,width:44
x:53,y:101,width:44
x:101,y:101,width:44




-------------------n=9---------------------
x:5,y:5,width:44
x:53,y:5,width:44
x:101,y:5,width:44
x:5,y:53,width:44
x:53,y:53,width:44
x:101,y:53,width:44
x:5,y:101,width:44
x:53,y:101,width:44
x:101,y:101,width:44