二维码生成使用的是一个第三方库:com.google.zxing 这个是什么自行百度吧。
制作一个带app logo的二维码
ImageView brImageView=new ImageView();
String brUrl="要生成二维码的链接(或者其他什么的事情看而定)";
//生成一个二维码bitmap width height
Bitmap qrBitmap = generateBitmap(brUrl,400, 400);
//在二维码中间生成一个logo所需要的bitmap
Bitmap logoBitmap = BitmapFactory.decodeResource(getResources(),“logo资源文件”);
//把二维码和logo绘制到一个bitmap上,然后显示在ImageView
Bitmap bitmap = addLogo(qrBitmap, logoBitmap);
bar_code.setImageBitmap(bitmap);
生成二维码bitmap
private Bitmap generateBitmap(String content,int width, int height) {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
Hashtable<EncodeHintType, String> hints = new Hashtable<>();
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合并成一个bitmap
private 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;
}