Android生成二维码通常使用ZXing库,其中提供了QRCodeWriter类。QRCodeWriter可将字符串编译为位矩阵BitMatrix,然后我们可以将位矩阵转为Int数组,通过bitmap.setPixels()方法将数组绘制于位图上。
1. 添加依赖
//Gradle Scripts -> build.gradle(Module:app)
implementation 'com.google.zxing:core:3.4.1'
implementation 'com.journeyapps:zxing-android-embedded:4.2.0'
2. 工具类
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.util.HashMap;
import java.util.Map;
public class QRCodeUtils {
/**
* 根据文本与容错值生成二维码位图
* @param text 文本
* @param errorCorrectionLevel 容错值
* @return 返回位图,如无文本内容返回null
*/
public Bitmap getQRBitmap(String text, ErrorCorrectionLevel errorCorrectionLevel) {
if(text==null){
return null;
}
//错误值
if(errorCorrectionLevel==null){
errorCorrectionLevel=ErrorCorrectionLevel.H;
}
int width = text.length() * 6; // 二维码图片的宽度
if(errorCorrectionLevel==ErrorCorrectionLevel.L){
width= (int) (width*1.5);
}
else if(errorCorrectionLevel==ErrorCorrectionLevel.Q){
width= (int) (width*2);
}
else if(errorCorrectionLevel==ErrorCorrectionLevel.M){
width= (int) (width*3);
}
else if(errorCorrectionLevel==ErrorCorrectionLevel.H){
width= (int) (width*4);
}
int height = width; // 二维码图片的高度
int margin = 1; // 二维码图片的空白边距
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.MARGIN, margin); // 设置空白边距
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 设置字符编码格式
hints.put(EncodeHintType.ERROR_CORRECTION, errorCorrectionLevel); // 设置容错率
try {
// 根据配置参数生成位矩阵对象
BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
// 创建像素数组,并根据位矩阵对象为数组元素赋色值
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (bitMatrix.get(x, y)) { // 返回true表示黑色色块
pixels[y * width + x] = Color.BLACK;
} else { // 返回false表示白色色块
pixels[y * width + x] = Color.WHITE;
}
}
}
// 创建位图对象,并根据像素数组设置每个像素的色值
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
//过小放大
if(width<500){
float i=500/width;
Matrix matrix=new Matrix();
matrix.setScale(i,i);
bitmap= Bitmap.createBitmap(bitmap,0,0,width,height,matrix,false);
}
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
return null;
}
}
}
3. 容错率
容错率即二维码允许损毁量。
ErrorCorrectionLevel.H 30%
ErrorCorrectionLevel.M 25%
ErrorCorrectionLevel.Q 15%
ErrorCorrectionLevel.L 7%