bitmap+文本生成新的bitmap的实现

  

注:参数content为生成二维码bitmap的内容,该二维码bitmap在和文本title组合生成一个新的bitmap

 

package info.ecloud.merchant.util;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.journeyapps.barcodescanner.BarcodeEncoder;

import java.util.Hashtable;



public class SaveImageUtils {

    private static final String CHARSET = "UTF-8";
    /**
     * 生成图片  加上title的图片
     * @param content
     * @param title
     * @return
     */
    public static Bitmap createImage(String content,String title) {
        int picWidth = 520;//生成图片的宽度
        int picHeight = 565;//生成图片的高度
        int titleTextSize = 25;
        int textColor = Color.BLACK;
        int qrWidth = 370;
        int qrHeight = 370;
        int paddingTop = 5;
        int paddingMiddle = 20;
        int paddingBottom = 20;

        //最终生成的图片
        Bitmap result = Bitmap.createBitmap(picWidth,picHeight,Bitmap.Config.ARGB_8888);

        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        Canvas canvas = new Canvas(result);

        //先画一整块白色矩形块
        canvas.drawRect(0,0,picWidth,picHeight,paint);

        //画title文字
        Rect bounds = new Rect();
        paint.setColor(textColor);
        paint.setTextSize(titleTextSize);
        //获取文字的字宽高,以便将文字与图片中心对齐
        paint.getTextBounds(title,0,title.length(),bounds);
        //画白色矩形块
        int qrTop = paddingTop+titleTextSize+paddingMiddle;//二维码的顶部高度

        //画二维码
        Hashtable hints = new Hashtable<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 5);
        Bitmap image = null;
        try {
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            image = barcodeEncoder.encodeBitmap((String) content, BarcodeFormat.QR_CODE, 400, 400);
        } catch (Exception e) {
            e.printStackTrace();
        }

        paint.setColor(Color.BLACK);
        canvas.drawBitmap(image,(picWidth-qrWidth)/2,qrTop,paint);

        //画文字
        paint.setColor(Color.BLACK);
        paint.setTextSize(titleTextSize);
        int line = 3;
        int textTop = qrTop+qrHeight+paddingBottom;//地址的顶部高度

        for (int i = 0 ; i < line ; i++){
            String[] split = title.split("-");
            paint.getTextBounds(title,0,split[i].length(),bounds);
            canvas.drawText(split[i],picWidth/2-bounds.width()/2,textTop+i*titleTextSize+i*5+bounds.height()/2,paint);
        }

        canvas.save();
        canvas.restore();

        return result;
    }


}

 

你可能感兴趣的:(bitmap+文本生成新的bitmap的实现)