很早就听说了zxing的大名了,一直没有机会使用,正好目前项目有了生成二维码的需求。就来试试吧。
一、先到Github上把项目下载下来把。 https://github.com/zxing/zxing
项目目录如下:
二、AndroidStudiodao导入上图android项目。
1、导入Android项目后,编译运行会发现丢失很多文件。
2、将上图中core、android-core。目录文件拷贝到对应文件夹,编译运行
三、找到生成二维码的功能
1、运行APP以后,找到编辑分享二维码内容页面ShareActivity
。在此页面编辑内容,然后跳转页面生成二维码
跳转到EncodeActivity二维码生成页面
2、找到生成二维码的页面EncodeActivity
。找到生成图片的地方
跳转到encodeAsBitmap方法。(笔记本截不了全部屏幕直接上代码吧)
Bitmap encodeAsBitmap() throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
BitMatrix result;
try {
result = new MultiFormatWriter().encode(contentsToEncode, format, dimension, dimension, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
到了这里在看看个个参数的含义就大功告成了。
引入jar包。http://repo1.maven.org/maven2/com/google/zxing/core/
在项目里我们不可能拷贝这么多代码进来,因此只要把核心jar包引用就可以了。下面是我引入jar文件以后的代码
/**
* 生成二维码
*
* @param contents 内容
* @param dimension 大小
* @return
* @throws WriterException
*/
public static Bitmap encodeAsBitmap(String contents, int dimension) throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
BitMatrix result;
try {
result = new MultiFormatWriter().encode(contentsToEncode, BarcodeFormat.QR_CODE, dimension, dimension, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}