Android将一张图放在另一张图的指定位置

package com.maiya.suixingou.common.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.text.TextUtils;

import com.maiya.core.common.utils.Utils;
import com.maiya.suixingou.R;
/**
 * Created by chenxiangxiang on 2019/1/24.
 */

public class BitmapUtils {

    public static int IMG_DEFAULT_WIDTH = 750;      //背景图的宽度
    public static int IMG_DEFAULT_HEIGHT = 1334;    //背景图的高度

    public static int QRCODE_X = 236;               //二维码位置X
    public static int QRCODE_Y = 886;               //二维码位置Y

    public static int TEXT_CENTER_X = 375;          //文字居中位置
    public static int TEXT_Y = 1262;                //文字y

    /**
     *
     * @param context
     * @param backBitmap 背景图
     * @param frontBitmap 上层图
     * @param inviteCode  需要绘制上去的文字
     * @param defBackImg  默认背景图
     * @return
     */
    public static Bitmap mergeBitmap(Context context, Bitmap backBitmap, Bitmap frontBitmap, String inviteCode,int defBackImg) {
        if (backBitmap == null || backBitmap.isRecycled() || frontBitmap == null || frontBitmap.isRecycled()) {
            backBitmap = BitmapFactory.decodeResource(context.getResources(), defBackImg);
        }
        backBitmap =scaleBitmap(backBitmap,IMG_DEFAULT_WIDTH,IMG_DEFAULT_HEIGHT);
        //合并bitmap
        Bitmap bitmap = Bitmap.createBitmap(IMG_DEFAULT_WIDTH, IMG_DEFAULT_HEIGHT, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(backBitmap, 0, 0, null);
        if(!Utils.isEmpty(frontBitmap)){
            canvas.drawBitmap(frontBitmap, QRCODE_X, QRCODE_Y, null);
        }
        if(!TextUtils.isEmpty(inviteCode)){
            Paint paint = new Paint();
            paint.setTextSize(sp2px(context, 20));
            paint.setColor(Color.WHITE);
            paint.setTextAlign(Paint.Align.CENTER);
            canvas.drawText(inviteCode, TEXT_CENTER_X, TEXT_Y, paint);
        }

        return bitmap;
    }

    private static Bitmap scaleBitmap(Bitmap bitmap,int defWith,int defHeght){
        //缩放
        float scaleX = 1.0f;
        float scaleY = 1.0f;
        if (bitmap.getWidth() != defWith) {
            scaleX = (defWith * 1.0f / bitmap.getWidth());
        }
        if (bitmap.getHeight() != defHeght) {
            scaleY = (defHeght * 1.0f / bitmap.getHeight());
        }
        Matrix matrix = new Matrix();
        matrix.postScale(scaleX, scaleY);
       return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
    }

    private static float sp2px(Context context, float sp) {
        final float scale = context.getResources().getDisplayMetrics().scaledDensity;
        return sp * scale;
    }
}

 

你可能感兴趣的:(android经验)