您的位置:首页 > 其它

解决zing生成二维码时二维码太小、白框太大的问题

2017-05-01 23:19 260 查看
  项目里实现生成二维码这个功能时,发现二维码的边框太大了,导致二维码内容区域太小。百度了一下,发现有人说设置EncodeHintType.MARGIN属性即可,这个属性值为1-4,实际测试发现并没有什么卵用。只好继续百度,最终找到了这个方法。

  

public static Bitmap Create2DCode(String str, int width, int height) {
try {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix matrix = new QRCodeWriter().encode(str, BarcodeFormat.QR_CODE, width, height, hint);
matrix = deleteWhite(matrix);//删除白边
width = matrix.getWidth();
height = matrix.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (matrix.get(x, y)) {
pixels[y * width + x] = Color.BLACK;
} else {
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);
return bitmap;
} catch (Exception e) {
return null;
}
}

private static BitMatrix deleteWhite(BitMatrix matrix) {
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;

BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1]))
resMatrix.set(i, j);
}
}
return resMatrix;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  安卓
相关文章推荐