android生成二维码

//第一步   导入依赖
compile 'com.mylhyl:zxingscanner:1.6.0'

//简单生成二维码  第一个为生成的参数
Bitmap bitmap = EncodingUtils.createQRCode("你好啊", 200, 200, null);
//iv为图片
iv.setImageBitmap(bitmap);


 
  
bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //第一个为二维码的内容
            Bitmap bt = generateBitmap("http://www.kugou.com/song/#hash=DBF4B8F33D594F4E411F595158E4AEB5&album_id=6704214", 500, 500);
            // iv.setImageBitmap(bt);

            //把图片转换成bitmap
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.qq);

            //第一个参数为生成的二维码   第二个为中间显示的图片
            Bitmap bitmap1 = addLogo(bt, bitmap);

            //给图片设置二维码
            iv.setImageBitmap(bitmap1);
        }
    });


}

//第一个参数为扫码后显示的内容   第二个为二维码的宽   第三个为二维码的高
private Bitmap generateBitmap(String content,int width, int height) {
    QRCodeWriter qrCodeWriter = new QRCodeWriter();
    Map 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;
}

//中间带图片的二维码
private Bitmap addLogo(Bitmap qrBitmap, Bitmap logoBitmap) {
    if (null==logoBitmap){
        Toast.makeText(MainActivity.this,"所选图片为空!",Toast.LENGTH_SHORT).show();
        return null;
    }
    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;
}

你可能感兴趣的:(android生成二维码)