1. 程式人生 > >Android生成自定義二維碼

Android生成自定義二維碼

/**
 *  生成自定義二維碼
 *
 * @param content                字串內容
 * @param width                  二維碼寬度
 * @param height                 二維碼高度
 * @param character_set          編碼方式(一般使用UTF-8)
 * @param error_correction_level 容錯率 L:7% M:15% Q:25% H:35%
 * @param margin                 空白邊距(二維碼與邊框的空白區域)
 * @param
color_black 黑色色塊 * @param color_white 白色色塊 * @param logoBitmap logo圖片(傳null時不新增logo) * @param logoPercent logo所佔百分比 * @param bitmap_black 用來代替黑色色塊的圖片(傳null時不代替) * @return */ public static Bitmap createQRCodeBitmap(String content, int width, int
height, String character_set, String error_correction_level, String margin, int color_black, int color_white, Bitmap logoBitmap, float logoPercent, Bitmap bitmap_black) { // 字串內容判空 if (TextUtils.isEmpty(content)) { return null; } // 寬和高>=0
if (width < 0 || height < 0) { return null; } try { /** 1.設定二維碼相關配置,生成BitMatrix(位矩陣)物件 */ Hashtable<EncodeHintType, String> hints = new Hashtable<>(); // 字元轉碼格式設定 if (!TextUtils.isEmpty(character_set)) { hints.put(EncodeHintType.CHARACTER_SET, character_set); } // 容錯率設定 if (!TextUtils.isEmpty(error_correction_level)) { hints.put(EncodeHintType.ERROR_CORRECTION, error_correction_level); } // 空白邊距設定 if (!TextUtils.isEmpty(margin)) { hints.put(EncodeHintType.MARGIN, margin); } /** 2.將配置引數傳入到QRCodeWriter的encode方法生成BitMatrix(位矩陣)物件 */ BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); /** 3.建立畫素陣列,並根據BitMatrix(位矩陣)物件為陣列元素賦顏色值 */ if (bitmap_black != null) { //從當前點陣圖按一定的比例建立一個新的點陣圖 bitmap_black = Bitmap.createScaledBitmap(bitmap_black, width, height, false); } int[] pixels = new int[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { //bitMatrix.get(x,y)方法返回true是黑色色塊,false是白色色塊 if (bitMatrix.get(x, y)) {// 黑色色塊畫素設定 if (bitmap_black != null) {//圖片不為null,則將黑色色塊換為新點陣圖的畫素。 pixels[y * width + x] = bitmap_black.getPixel(x, y); } else { pixels[y * width + x] = color_black; } } else { pixels[y * width + x] = color_white;// 白色色塊畫素設定 } } } /** 4.建立Bitmap物件,根據畫素陣列設定Bitmap每個畫素點的顏色值,並返回Bitmap物件 */ Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); /** 5.為二維碼新增logo圖示 */ if (logoBitmap != null) { return addLogo(bitmap, logoBitmap, logoPercent); } return bitmap; } catch (WriterException e) { e.printStackTrace(); return null; } }