环境:androidstudio2.3.2
zxing git源码路径 https://github.com/zxing/zxing
AndroidStudio引用该库:
dependencies {
compile fileTree(dir: ‘libs’, include: [‘*.jar’])
compile ‘com.android.support:appcompat-v7:25.3.1’
compile ‘com.google.zxing:core:3.2.1’
}
使用代码
/**
* 生成QRCode二维码
*
* @param data
* @param size qr二维码为正方形码,宽高一致
* @return
*/
private Bitmap generateQRCodeBitmap(String data, int size) {
return generateQRCodeBitmap(data, size, size);
}
private Bitmap generateQRCodeBitmap(String data, int width, int height) {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Map<EncodeHintType, Object> hints = new HashMap<>();
//编码
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//容错率
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);
int margin = 1; //自定义白边边框宽度
//二维码边框宽度
hints.put(EncodeHintType.MARGIN, margin);
try {
BitMatrix encode = qrCodeWriter.encode(data, BarcodeFormat.QR_CODE, width, height, hints);
int[] pixels = new int[width * height];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (encode.get(j, i)) {
pixels[i * width + j] = 0x00000000;
} else {
pixels[i * width + j] = 0xffffffff;
}
}
}
return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
其他:
解析二维码,参考:http://blog.csdn.net/xiaanming/article/details/10163203
去除白边或进行放缩:http://blog.csdn.net/jdsjlzx/article/details/45268815