android studio 在 gradle 中加入配置, compile 'com.google.zxing:core:3.2.1'
content 是 http的url, widthPix 和 heightPix 是要生成bitmap 的大小,然后调用方法
public static Bitmap createQRImage(String content, int widthPix, int heightPix) {
if (!TextUtils.isEmpty(content)) {
try {
//配置参数
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置空白边距的宽度
hints.put(EncodeHintType.MARGIN, 0); //系统默认是有白边了,这里设置为0后就会没有白边了
// 图像数据转换,使用了矩阵转换
BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
int[] pixels = new int[widthPix * heightPix];
// 下面这里按照二维码的算法,逐个生成二维码的图片,
// 两个for循环是图片横列扫描的结果
for (int y = 0; y < heightPix; y++) {
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = 0xff000000;
} else {
pixels[y * widthPix + x] = 0xffffffff;
}
}
}
// 生成二维码图片的格式,使用ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
最简单的解决方式:
其实网上很多方式都是通过生成矩阵后,重新获取然后去裁剪操作,这样相当于多了一项工作,我们只要给生成的 BitMatrix
添加属性 hints.put(EncodeHintType.MARGIN, 0); 这样出来的二维码是没有白色边框的。
设置白色边框:
如果要想显示不那么宽的白色边,然后给显示二维码的ImageView 添加一个src 前置背景就可以 然后内部Padding一下调整间距就可以了
本文介绍了如何在Android中生成无白边的二维码。关键在于修改二维码生成的配置,通过设置`EncodeHintType.MARGIN`为0来消除边距。此外,还提供了解决方案,如果需要调整边框宽度,可以通过给ImageView添加背景并设置适当的Padding来实现。

2581

被折叠的 条评论
为什么被折叠?



