二维码的使用

先导入jar包如下图所示;


在开始前先生成qrwriter实例:

       //获取一个QRCodeWriter实例
        QRCodeWriter writer = new QRCodeWriter();
        Map<EncodeHintType, Object> hints = new HashMap<>();
        //设置文本的编码格式
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //设置容错级别,共分为4级
        //容错率越高,生成的二维码越复杂,识别时的速度越慢
//        L,容错率7%
//        M,容错率15%
//        Q,容错率25%
//        H,容错率30%
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);

第一步对文本进行编码:

  BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
第二步生成色彩点阵:

    BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] colors = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    //如果该点有数据,则该点的颜色为黑色,否则为白色
                    if (bitMatrix.get(j, i)) {
                        colors[i * width + j] = 0x000000;
                    } else {
                        colors[i * width + j] = 0xffffff;
                    }
                }
            }

第三步根据点阵生成图片

 Bitmap bitmap = Bitmap.createBitmap(colors, 0, width, width, height, Bitmap.Config.RGB_565);
一张二维码图片就生成了
插入logo图片:

  private Bitmap addLogo(Bitmap qrCodeBitmap, Bitmap logoBitmap) {
        int qrCodeBitmapWidth = qrCodeBitmap.getWidth();
        int qrCodeBitmapHeight = qrCodeBitmap.getHeight();
        int logoBitmapWidth = logoBitmap.getWidth();
        int logoBitmapHeight = logoBitmap.getHeight();
        //创建一个空白的Bitmap,该Bitmap的大小和二维码所对应的Bitmap的大小一致
        Bitmap blankBitmap = Bitmap.createBitmap(qrCodeBitmapWidth, qrCodeBitmapHeight, Bitmap.Config.ARGB_8888);
        //创建一个Canvas对象,使用空白Bitmap作为参数,这样在Canvas上所绘制的所有东西都可以通过Bitmap显示出来
        Canvas canvas = new Canvas(blankBitmap);
        //将二维码的Bitmap绘制到canvas上
        canvas.drawBitmap(qrCodeBitmap, 0, 0, null);
        //绘制Logo,如果Logo过大,通过Bitmap二次采样来处理
        canvas.drawBitmap(logoBitmap, (qrCodeBitmapWidth - logoBitmapWidth) / 2,
                (qrCodeBitmapHeight - logoBitmapHeight) / 2, null);
        return blankBitmap;
    }

添加logo:

Bitmap qrCodeBitmap = getQRCodeBitmap(200, 200, qrCodeText.getText().toString());
        Bitmap logoBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        Bitmap bitmap = addLogo(qrCodeBitmap, logoBitmap);
        iv.setImageBitmap(bitmap);
下面是jar包链接:

http://pan.baidu.com/s/1qY0OS36


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值