android使用qrcode_swetake.jar生成二维码

只有生成二维码的代码

优点是占用方法数比较少 以防65535

 

    static Paint paint;

    static {
        paint = new Paint(); // 设置一个笔刷大小是1的黑色的画笔
        paint.setColor(Color.BLACK);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        paint.setStrokeWidth(1);
    }

    private static final int RECT_SIZE = 6;
    private static final int PIX_OFF = 2;//设置偏移量 不设置可能导致解析出错

    /**
     * 生成二维码(QRCode)图片
     *
     * @param content
     * @param
     */
    public static Bitmap encoderQRCode(String content) {
        Canvas g;
        try {
            Qrcode qrcodeHandler = new Qrcode();
            // 设置二维码排错率,可选L(7%)、M(15%)、Q(25%)、H(30%),排错率越高可存储的信息越少,但对二维码清晰度的要求越小
            qrcodeHandler.setQrcodeErrorCorrect('L');
            //N(Numeric,数字), A(Alphanumeric,英文字母), B(Binary,二进制), K(Kanji,汉字)
            qrcodeHandler.setQrcodeEncodeMode('B');
            int version = 4;//1-40 共40个版本 ,版本1(21x21模块), 版本40(177x177模块), 每增加一个版本每边增加4个模块 ,如: 版本4 21+(4-1)*4=33 为33x33模块
            qrcodeHandler.setQrcodeVersion(version);

            int PIC_SIZE = RECT_SIZE * (21 + (4 * (version - 1))) + 2 * PIX_OFF;
            byte[] contentBytes = content.getBytes("utf-8");
            Bitmap bufferBitMap = Bitmap.createBitmap(PIC_SIZE, PIC_SIZE, Bitmap.Config.ARGB_8888);
            g = new Canvas(bufferBitMap);
            g.drawColor(Color.TRANSPARENT);
            // 输出内容 > 二维码
            if (contentBytes.length > 0 && contentBytes.length < 512) {
                boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
                for (int i = 0; i < codeOut.length; i++) {
                    for (int j = 0; j < codeOut.length; j++) {
                        if (codeOut[j][i]) {
                            float left = j * RECT_SIZE + PIX_OFF;
                            float top = i * RECT_SIZE + PIX_OFF;
                            float right = (j + 1) * RECT_SIZE + PIX_OFF;
                            float bottom = (i + 1) * RECT_SIZE + PIX_OFF;
                            g.drawRect(left, top, right, bottom, paint);
                        }
                    }
                }
            } else {
                Log.e("QRCodeEncoderHandler", "QRCode content bytes length = " + contentBytes.length
                        + " not in [ 0,120 ]. ");
            }
            return bufferBitMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

 

posted @ 2015-06-11 18:28  一枚攻城尸  阅读(530)  评论(0编辑  收藏  举报