【GT-安卓应用开发之合成长图】

前言:刚才看微博,看到很多长图。一时兴起,想通过代码制作一张长图并展示。我的思路是利用Canvas将多张照片依次合成,并在外层套用一个ScrollView展示图片以及保存本地。

        效果图如下:

        

        关键代码:

public static Bitmap newBitmap(Bitmap bmp1, Bitmap bmp2) {
    Bitmap retBmp;
    int width =bmp1.getWidth() ;
    if (bmp2.getWidth() != width) {
        //以第一张图片的宽度为标准,对第二张图片进行缩放。
        int h2 = bmp2.getHeight() * width / bmp2.getWidth();
        retBmp = Bitmap.createBitmap(width, bmp1.getHeight() + h2, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(retBmp);
        Bitmap newSizeBmp2 = resizeBitmap(bmp2, width, h2);
        canvas.drawBitmap(bmp1, 0, 0, null);
        canvas.drawBitmap(newSizeBmp2, 0, bmp1.getHeight(), null);
    } else {
        //两张图片宽度相等,则直接拼接。

        retBmp = Bitmap.createBitmap(width, bmp1.getHeight() + bmp2.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(retBmp);
        canvas.drawBitmap(bmp1, 0, 0, null);
        canvas.drawBitmap(bmp2, 0, bmp1.getHeight(), null);
    }
    img.setImageBitmap(retBmp);

    return retBmp;
}

public static Bitmap resizeBitmap(Bitmap bitmap, int newWidth, int newHeight) {
    float scaleWidth = ((float) newWidth) / bitmap.getWidth();
    float scaleHeight = ((float) newHeight) / bitmap.getHeight();
    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);
    Bitmap bmpScale = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    return bmpScale;
}

/**
 * 保存图片到文件File。
 *
 * @param src     源图片
 * @param file    要保存到的文件
 * @param format  格式
 * @param recycle 是否回收
 * @return true 成功 false 失败
 */
public static boolean save(Bitmap src, File file, Bitmap.CompressFormat format, boolean recycle) {
    if (isEmptyBitmap(src))
        return false;

    OutputStream os;
    boolean ret = false;
    try {
        os = new BufferedOutputStream(new FileOutputStream(file));
        ret = src.compress(format, 100, os);
        if (recycle && !src.isRecycled())
            src.recycle();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return ret;
}

/**
 * Bitmap对象是否为空。
 */
public static boolean isEmptyBitmap(Bitmap src) {
    return src == null || src.getWidth() == 0 || src.getHeight() == 0;
}

        最后,完整项目源码地址

猜你喜欢

转载自blog.csdn.net/qq_17433217/article/details/83039831
今日推荐