開發中需將資訊轉為帶公司 Logo 的二維碼。Google ZXING 開源庫支援條碼/二維碼生成與解析,但官方無帶 Logo 範例。本文透過實例說明實作細節。

專案引入 core.jar(ZXING 核心庫)。專案地址:github.com/zxing/zxing
encode() 產生 BitMatrixget(x,y) 判斷該位置是否為黑塊,配合 Bitmap.setPixels() 繪製圖像public Bitmap createCode(String content, Bitmap logo, BarcodeFormat format) throws WriterException {
// 縮放 Logo
Matrix m = new Matrix();
float sx = (float) 2 * IMAGE_HALFWIDTH / logo.getWidth();
float sy = (float) 2 * IMAGE_HALFWIDTH / logo.getHeight();
m.setScale(sx, sy);
logo = Bitmap.createBitmap(logo, 0, 0, logo.getWidth(), logo.getHeight(), m, false);
// 生成二維碼矩陣
MultiFormatWriter writer = new MultiFormatWriter();
Hashtable<EncodeHintType, String> hints = new Hashtable<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix matrix = writer.encode(content, format, 400, 400, hints);
int width = matrix.getWidth();
int height = matrix.getHeight();
int halfW = width / 2, halfH = height / 2;
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// 中央區域放 Logo
if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH
&& y > halfH - IMAGE_HALFWIDTH && y < halfH + IMAGE_HALFWIDTH) {
pixels[y * width + x] = logo.getPixel(x - halfW + IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);
} else if (matrix.get(x, y)) {
pixels[y * width + x] = 0xFF000000; // 黑塊
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
完整 Activity 代碼包含 UI 綁定、vCard 格式字串組裝、點擊生成並顯示於 ImageView。完整代碼見原文。