Android 二維碼相關(一) 本篇文章主要記錄下android下使用zxing來創建二維碼. 1: 導入依賴 api "com.google.zxing:core:3.5.1" 2: 創建二維碼 創建QRCodeWriter對象 QRCodeWriter qrCodeWriter = new Q ...
Android 二維碼相關(一)
本篇文章主要記錄下android下使用zxing來創建二維碼.
1: 導入依賴
api "com.google.zxing:core:3.5.1"
2: 創建二維碼
-
創建QRCodeWriter對象
QRCodeWriter qrCodeWriter = new QRCodeWriter();
-
將文本內容轉換成BitMatrix
BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, size, size);
-
創建bitmap
Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565);
-
將BitMatrix渲染到bitmap
for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { //將BitMatrix渲染到bitmap bitmap.setPixel(x, y, encode.get(x, y) ? Color.BLACK : Color.WHITE); } }
完整的代碼如下:
public class QRCodeUtils {
private static final String TAG = "QRCodeUtils";
/**
* @param content 字元串內容
* @param size 點陣圖寬&高(單位:px)
* @return
*/
public static Bitmap createQRCodeBitmap(String content, int size) {
if (TextUtils.isEmpty(content)) return null;
if (size <= 0) return null;
//創建QRCodeWriter對象
QRCodeWriter qrCodeWriter = new QRCodeWriter();
try {
//使用QRCodeWriter將文本內容轉換成BitMatrix.
BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, size, size);
Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565);
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
//將BitMatrix渲染到bitmap
bitmap.setPixel(x, y, encode.get(x, y) ? Color.BLACK : Color.WHITE);
}
}
return bitmap;
} catch (Throwable e) {
Log.e(TAG, "createQRCodeBitmap: ", e);
}
return null;
}
}
3: 給二維碼添加logo
給二維碼添加logo 與上篇文章添加水印類似.
都是通過canvas重新繪製,合成圖片.
具體的代碼如下:
/**
* @param srcBitmap 二維碼
* @param logoBitmap 二維碼logo
* @param logoPercent 二維碼logo的占比 [0,1]
* @return
*/
public static Bitmap addQRCodeLogo(Bitmap srcBitmap, Bitmap logoBitmap, float logoPercent) {
//校驗參數合法
if (srcBitmap == null) return null;
if (logoBitmap == null) return srcBitmap;
if (logoPercent < 0 || logoPercent > 1) logoPercent = 0.2f;
//原圖/logo的寬高
int srcWidth = srcBitmap.getWidth();
int srcHeight = srcBitmap.getHeight();
int logoHeight = logoBitmap.getHeight();
int logoWidth = logoBitmap.getWidth();
//縮放
float scaleWidth = srcWidth * logoPercent / logoWidth;
float scaleHeight = srcHeight * logoPercent / logoHeight;
//使用Canvas繪製
Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(srcBitmap, 0, 0, null);
canvas.scale(scaleWidth, scaleHeight, srcWidth / 2, srcHeight / 2);
canvas.drawBitmap(logoBitmap, srcWidth / 2-logoWidth/2, srcHeight / 2-logoHeight/2, null);
return bitmap;
}
新增創建二維碼方法:
/**
* @param content 字元串內容
* @param size 點陣圖寬&高(單位:px)
* @param logo 二維碼logo
* @param logoPercent 二維碼logo的占比 [0,1]
* @return
*/
public static Bitmap createQRCodeBitmap(String content, int size, Bitmap logo, float logoPercent) {
Bitmap qrCodeBitmap = createQRCodeBitmap(content, size);
Bitmap bitmap = addQRCodeLogo(qrCodeBitmap, logo, logoPercent);
return bitmap;
}
本文由博客一文多發平臺 OpenWrite 發佈!