Android overlays two bitmaps into one bitmap.

The QR code scanning function is needed in recent projects, but the QR code is a dynamic background image, so it needs two pictures to be combined for the user to scan, so the two bitmaps need to be combined into one bitmap.

public static Bitmap mergeBitmap(Bitmap backBitmap, Bitmap frontBitmap) {
    if (backBitmap == null || backBitmap.isRecycled()
            || frontBitmap == null || frontBitmap.isRecycled()) {
        return null;
    }
    //创建新的位图,宽高为背景位图的宽高。
    Bitmap newBitmap = Bitmap.createBitmap(backBitmap.getWidth(), backBitmap.getHeight(), Bitmap.Config.ARGB_8888);
    //创建画布
    Canvas canvas = new Canvas(newBitmap);
    //绘制背景图,从左上角为坐标为0 0的位置绘制。
    canvas.drawBitmap(backBitmap, 0, 0, null);
    //绘制需要覆盖至上方的位图,绘制的位置为背景图的右下角减去上方位图的宽高(也就是在新位图的右下角位置)
    canvas.drawBitmap(frontBitmap, backBitmap.getWidth() - frontBitmap.getWidth(),backBitmap.getHeight() - frontBitmap.getHeight(), null);
    //创建画笔
    Paint paint = new Paint();
    //设置需要绘制的文字的大小
    paint.setTextSize(3);
    //设置需要绘制的文字的颜色
    paint.setColor(Color.parseColor("#24A4FF"));
    //创建一个矩形
    Rect bounds = new Rect();
    //需要绘制的文字
    String text = "长按识别二维码";
    //把文字放至矩形中
    paint.getTextBounds(text, 0, text.length(), bounds);
    //绘制文字
    canvas.drawText(text, backBitmap.getWidth() - (frontBitmap.getWidth() + bounds.width()) / 2 - 2,
            backBitmap.getHeight() - 12, paint);
    canvas.save();
    canvas.restore();
    return newBitmap;
}

Guess you like

Origin blog.csdn.net/qq77485042/article/details/102501103