工具类
//生成二维码
public Bitmap createQRCodeBitmap(String code_url) {
// 用于设置QR二维码参数
final Hashtable<EncodeHintType, Object> qrParam = new Hashtable<EncodeHintType, Object>();
// 设置QR二维码的纠错级别――这里选择最高H级别
qrParam.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 设置编码方式
qrParam.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 设定二维码里面的内容
// final String content = content;
// 生成QR二维码数据――这里只是得到一个由true和false组成的数组
// 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
int QRCODE_SIZE = DensityUtil.dip2px(this, 360);
try {
final BitMatrix bitMatrix = new MultiFormatWriter().encode(code_url,
BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, qrParam);
// 开始利用二维码数据创建Bitmap图片,分别设为黑白两色
final int w = bitMatrix.getWidth();
final int h = bitMatrix.getHeight();
final int[] data = new int[w * h];
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
if (bitMatrix.get(x, y))
// data[y * w + x] = 0xff19b393;// 标题的颜色
data[y * w + x] = 0xff000000;
else
data[y * w + x] = -1;// -1 相当于0xffffffff 白色
}
}
// 创建一张bitmap图片,采用最高的图片效果ARGB_8888
final Bitmap bitmap = Bitmap.createBitmap(w, h,
Bitmap.Config.ARGB_8888);
// 将上面的二维码颜色数组传入,生成图片颜色
bitmap.setPixels(data, 0, w, 0, 0, w, h);
return bitmap;
} catch (final WriterException e) {
e.printStackTrace();
}
return null;
}
用法
@BindView(R.id.image_qr)
ImageView image_qr;
Bitmap bitmap = createQRCodeBitmap("https://blog.csdn.net/weixin_44177244/article/details/108723749");
image_qr.setImageBitmap(bitmap);