使用Zxing玩转二维码白边的各个花样

本文介绍了如何使用Zxing库生成二维码,深入解析了二维码白边的生成过程,并提供了去掉和自定义白边颜色的方法。此外,还展示了如何在二维码上添加LOGO和文字段落。
摘要由CSDN通过智能技术生成

1.生成二维码

简单介绍一下Zxing二维码库的使用方式,Zxing库很强大,可以生成各种格式的二维码(分析源码部分时再看其他的类型),最常用的就是QR格式。

1.1代码

如果没有Zxing库,可以到我的云盘下载。
把jar包下载,copy到工程的libs目录下,buildpath即可

1.1.1 获取编码后的数据Bitmatrix

BitMatrix是Zxing库定义的一个二维码的数据类。
这个方法主要是生成二维码的BitMatrix,实际上就是一个矩阵,二维数组–!
获取到Bitmap后,就可以随意展示了

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static Bitmap generateQRCode(String content, int width, int height) {
        try {
            HashMap hints = new HashMap();
            // 设置编码方式utf-8
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8" );
            //设置二维码的纠错级别为h
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            BitMatrix matrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);
            return bitMatrix2Bitmap(matrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null ;
    }
1.1.2将数据Bitmatrix转换成Bitmap
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private static Bitmap bitMatrix2Bitmap(BitMatrix matrix) {
        matrix = updateBit(matrix, 0 );
        int w = matrix.getWidth();
        int h = matrix.getHeight();
        int [] rawData = new int [w * h];
        for ( int i = 0 ; i < w; i++) {
            for ( int j = 0 ; j < h; j++) {
                int color = Color.WHITE;
                if (matrix.get(i, j)) {
                        // 有内容的部分,颜色设置为黑色,当然这里可以自己修改成喜欢的颜色
                    color = Color.BLACK;
                }
                rawData[i + (j * w)] = color;
            }
        }
 
        Bitmap bitmap = Bitmap.createBitmap(w, h, Config.RGB_565);
        bitmap.setPixels(rawData, 0 , w, 0 , 0 , w, h);
        return bitmap;
    }

2.源码分析白边的生成过程

下面就分析Zxing的源码以及默认白边的形成
先看generateQRCode里的关键方法MultiFormatWriter类的encode方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map hints) throws WriterException {
          Writer writer;
          switch (format) {
              case EAN_8:
            writer = new EAN8Writer();
            break ;
          case EAN_13:
            writer = new EAN13Writer();
            break ;
        case UPC_A:
            writer = new UPCAWriter();
           break ;
         case QR_CODE:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值