上段代码可以看出要给二维码图片中间加logo,但是图片不能占据整个二维码图片的很大一部分。然后还必须设置容错率:容错率有M,L,Q,H几个等级,容错率越高,二维码的有效像素点就越多。这里使用小写的utf-8编码,大写会出现]Q2 00026开头内容,为了好看点还设置了边距和大小。
第三步:实现带logo的彩色二维码
接下来我们把黑白矩阵变为彩色矩阵:
就把
if (bitMatrix.get(x, y)) pixels[y * width + x] = 0xff000000; else pixels[y * width + x] = 0xffffffff;
替换为:(这里的颜色随便设置,效果随便改)
if (x < QR_WIDTH / 2 && y < QR_HEIGHT / 2) {
pixels[y * QR_WIDTH + x] = 0xFF0094FF;// 蓝色
Integer.toHexString(new Random().nextInt());
} else if (x < QR_WIDTH / 2 && y > QR_HEIGHT / 2) {
pixels[y * QR_WIDTH + x] = 0xFFFED545;// 黄色
} else if (x > QR_WIDTH / 2 && y > QR_HEIGHT / 2) {
pixels[y * QR_WIDTH + x] = 0xFF5ACF00;// 绿色
} else {
pixels[y * QR_WIDTH + x] = 0xFF000000;// 黑色
}
} else {
pixels[y * QR_WIDTH + x] = 0xffffffff;// 白色
}
改后的效果:
第四步:给二维码加背景
接下来我们来给二维码图片加背景:
/**
* 给二维码图片加背景
*
*/
public static Bitmap addBackground(Bitmap foreground,Bitmap background){
int bgWidth = background.getWidth();
int bgHeight = background.getHeight();
int fgWidth = foreground.getWidth();
int fgHeight = foreground.getHeight();
Bitmap newmap = Bitmap
.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newmap);
canvas.drawBitmap(background, 0, 0, null);
canvas.drawBitmap(foreground, (bgWidth - fgWidth) / 2,
(bgHeight - fgHeight) *3 / 5+70, null);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
return newmap;
}











