天天看點

Android圖檔拼接9宮格

/**
     * 多張圖檔拼接9宮格
     * @param margin
     * @param bitmaps
     * @return
     */
    public static Bitmap addBitmaps(int margin, Bitmap... bitmaps) {
        int row=1;
        int col=0;
        int width = 0;
        int height = 0;
        int totalHeight = 0;
        int length = bitmaps.length;
        if(length>3){
            row=length%3==0?length/3:length/3+1;
            col=3;
        }else{
            row=1;
            col=length;
        }
        for (int i = 0; i < length; i++) {
            height = Math.max(height, bitmaps[i].getHeight());
        }
        totalHeight=height*row;
        totalHeight+=(row-1)*margin;

        for (int i = 0; i < col; i++) {
            width += bitmaps[i].getWidth();
            width += margin;
        }
        width -= margin;
        Bitmap result = Bitmap.createBitmap(width, totalHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        for (int i = 0; i < row; i++) {
            int left = 0;
            for (int i1 = 0; i1 < col; i1++) {
                if(i*col+i1 >=length){
                    break;
                }
                if(i>0){
                    if(i1>0){
                        left += bitmaps[i*col+i1-1].getWidth();
                        left += margin;
                        int top=(height+margin)*i;
                        canvas.drawBitmap(bitmaps[i*col+i1], left,top, null);
                    }else{
                        left =0;
                        left += margin;
                        int top=(height+margin)*i;
                        canvas.drawBitmap(bitmaps[i*col+i1], left,top, null);
                    }
                }else{
                    //第1行
                    if(i1>0){
                        left += bitmaps[i1-1].getWidth();
                        left += margin;
                        canvas.drawBitmap(bitmaps[i1], left,0, null);
                    }else{
                        left =0;
                        left += margin;
                        canvas.drawBitmap(bitmaps[i1], left,0, null);
                    }
                }
            }
        }
        return result;
    }
           
Android圖檔拼接9宮格