Android 拼接多张图片成宫格

需求

照片排列公式:照片数x,开根号,向上取整是列数y;x/y,向上取整是行数z;y*z-x,是需补齐的照片数;列数有1-10的十种情况;例如照片44张,则显示7行7列,最后一行最后5张自动重复开始的5张;

效果图

image.png

代码

/**
     * 多张图片拼接宫格
     *
     * @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;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容