Android 二维码相关(一)
本篇文章主要记录下android下使用zxing来创建二维码.
1: 导入依赖
java
api "com.google.zxing:core:3.5.1"
2: 创建二维码
-
创建QRCodeWriter对象
javaQRCodeWriter qrCodeWriter = new QRCodeWriter();
-
将文本内容转换成BitMatrix
javaBitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, size, size);
-
创建bitmap
javaBitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565);
-
将BitMatrix渲染到bitmap
javafor (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); } }
完整的代码如下:
java
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重新绘制,合成图片.
具体的代码如下:
java
/**
* @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;
}
新增创建二维码方法:
java
/**
* @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;
}