转载请注明出处:http://www.jianshu.com/p/bc2b95c2044d
本文出自Shawpoo的简书
我的博客:CSDN博客
最近在开发项目中,需要在APP中生成二维码,我使用的Google Zxing的库:
点击下载Zxing-core.jar
1、生成二维码图片
/**
* 生成二维码图片
*
* @param str 二维码内容
* @return
*/
public static Bitmap createBarcode(String str) {
Bitmap bitmap = null;
BitMatrix result = null;
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
result = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 260, 260);
int w = result.getWidth();
int h = result.getHeight();
int[] pixels = new int[w * h];
for (int y = 0; y < h; y++) {
int offset = y * w;
for (int x = 0; x < w; x++) {
pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.WHITE;
}
}
bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, w, 0, 0, w, h);
} catch (WriterException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return bitmap;
}
2、为二维码增加Logo图
/**
* 为二维码增加logo图片
*
* @param qrBitmap
* @param logoBitmap
* @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;
}
3、直接调用
Bitmap qrBitmap = createBarcode(mUrl);
Bitmap logoBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);