二维码生成和保存的小常识:一般zxing自动生成的二维码是根据坐标来绘制黑色点,来生成最后的二维码,但是白色区域其实是没有绘制的,理论上是透明色,但为什么把生成的bitmap设置到imageview中却显示正确呢,原来视音频的imageview在显示的时候会把没有颜色的位置默认使用白色替代。但如果保存的时候会使用黑色替代。最后导致图库里的图片是一张纯黑色图片。解决办法就是在绘制二维码的时候同时把白色坐标点绘制颜色,当然可以是任意颜色,一般还是为白色,这样无论是显示还是保存的时候都会正常了。
public static Bitmap createQRCode(String str, int widthAndHeight)
throws WriterException {
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix matrix = new MultiFormatWriter().encode(str,
BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
int width = matrix.getWidth();
int height = matrix.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (matrix.get(x, y)) {
pixels[y * width + x] = BLACK;
}else{
pixels[y * width + x] = Color.WHITE;
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
重点就在:else{
pixels[y * width + x] = WHITE;
}这句话