ZXing生成二维码的边距问题

使用ZXing的 QRCodeWriter().encode方法生成的二维码往往边距有问题。

图片来自下方链接

详细原因已经有人分析过了。

我也用了一个简单粗暴但性能不高的方法:将二维码抠出来显示。以下是具体实现:
1、生成二维码矩阵:

BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, widthPx, heightPx, hints);

2、找出二维码具体区域:

int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();

Rect bounds = new Rect();
bounds.left = Integer.MAX_VALUE;
bounds.top = Integer.MAX_VALUE;

for (int h = 0; h < height; h++) {
   for (int w = 0; w < width; w++) {
       if (bitMatrix.get(w, h)) {
           if (bounds.left > w) bounds.left = w;
           if (bounds.top > h) bounds.top = h;
       }
   }
}

for (int h = height - 1; h >= 0; h--) {
   for (int w = width - 1; w >= 0; w--) {
       if (bitMatrix.get(w, h)) {
           if (bounds.right < w) bounds.right = w;
           if (bounds.bottom < h) bounds.bottom = h;
       }
   }
}

3、生成Bitmap:

int[] pixels = new int[bounds.width() * bounds.height()];
int x = 0;
int y = 0;
for (int h = bounds.top; h < bounds.bottom; h++) {
    for (int w = bounds.left; w < bounds.right; w++) {
        pixels[y * bounds.width() + x] = bitMatrix.get(w, h) ? 0xff000000 : 0x00ffffff;
        x++;
    }
    x = 0;
    y++;
}

简单实现 代码没有优化。记录一下。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。