Android之二维码(生成)

二维码,相信大家有不陌生,现在主流的app,例如微信支付宝等等,几乎都会有二维码的功能,所谓是非常之广泛。

二维码分为2个部分,一个是生成,一个是识别,这里我们先来讲讲二维码是如何生成的。

二维码的开发使用我们大多都是使用Google提供的zxing这个类库,使用这个类库我们需要先下载核心jar包,jar包下载地址,如果我们只想生成二维码那么这个就够了。

下载之后添加:
这里写图片描述

看代码:


    /**
     *  生成二维码图片
     */
        private Bitmap generateBitmap(String content,int width, int height) {  
        QRCodeWriter qrCodeWriter = new QRCodeWriter();  
        Map<EncodeHintType, String> hints = new HashMap<>();  
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");  
        try {  
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);  
            int[] pixels = new int[width * height];  
            for (int i = 0; i < height; i++) {  
                for (int j = 0; j < width; j++) {  
                    if (encode.get(j, i)) {  
                        pixels[i * width + j] = 0x00000000;  
                    } else {  
                        pixels[i * width + j] = 0xffffffff;  
                    }  
                }  
            }  
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);  
        } catch (WriterException e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  


    /**
     * 给二维码中间加logo图片
     *
     * @param qrBitmap   二维码图片
     * @param logoBitmap logo图片
     * @return
     */
    public static Bitmap addLogo(Bitmap qrBitmap, Bitmap logoBitmap) {
        int qrBitmapWidth = qrBitmap.getWidth();
        int qrBitmapHeight = qrBitmap.getHeight();
        int logoBitmapWidth = logoBitmap.getWidth();
        int logoBitmapHeight = logoBitmap.getHeight();
        Bitmap blankBitmap = Bitmap.createBitmap(qrBitmapWidth, qrBitmapHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(blankBitmap);
        canvas.drawBitmap(qrBitmap, 0, 0, null);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        float scaleSize = 1.0f;
        while ((logoBitmapWidth / scaleSize) > (qrBitmapWidth / 5) || (logoBitmapHeight / scaleSize) > (qrBitmapHeight / 5)) {
            scaleSize *= 2;
        }
        float sx = 1.0f / scaleSize;
        canvas.scale(sx, sx, qrBitmapWidth / 2, qrBitmapHeight / 2);
        canvas.drawBitmap(logoBitmap, (qrBitmapWidth - logoBitmapWidth) / 2, (qrBitmapHeight - logoBitmapHeight) / 2, null);
        canvas.restore();
        return blankBitmap;
    }

基本使用:

这里写图片描述

这里我就不提供效果图了,基本上就是这样了,很简单哦!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值