註:參數content為生成二維碼bitmap的內容,該二維碼bitmap在和文本title組合生成一個新的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<EncodeHintType, Object> 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; } }