1.生成二维码
简单介绍一下Zxing二维码库的使用方式,Zxing库很强大,可以生成各种格式的二维码(分析源码部分时再看其他的类型),最常用的就是QR格式。
1.1代码
如果没有Zxing库,可以到我的云盘下载。
把jar包下载,copy到工程的libs目录下,buildpath即可
1.1.1 获取编码后的数据Bitmatrix
BitMatrix是Zxing库定义的一个二维码的数据类。
这个方法主要是生成二维码的BitMatrix,实际上就是一个矩阵,二维数组–!
获取到Bitmap后,就可以随意展示了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public
static
Bitmap generateQRCode(String content,
int
width,
int
height) {
try
{
HashMap hints =
new
HashMap();
// 设置编码方式utf-8
hints.put(EncodeHintType.CHARACTER_SET,
"utf-8"
);
//设置二维码的纠错级别为h
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
BitMatrix matrix =
new
MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, width, height, hints);
return
bitMatrix2Bitmap(matrix);
}
catch
(WriterException e) {
e.printStackTrace();
}
return
null
;
}
|
1.1.2将数据Bitmatrix转换成Bitmap
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
private
static
Bitmap bitMatrix2Bitmap(BitMatrix matrix) {
matrix = updateBit(matrix,
0
);
int
w = matrix.getWidth();
int
h = matrix.getHeight();
int
[] rawData =
new
int
[w * h];
for
(
int
i =
0
; i < w; i++) {
for
(
int
j =
0
; j < h; j++) {
int
color = Color.WHITE;
if
(matrix.get(i, j)) {
// 有内容的部分,颜色设置为黑色,当然这里可以自己修改成喜欢的颜色
color = Color.BLACK;
}
rawData[i + (j * w)] = color;
}
}
Bitmap bitmap = Bitmap.createBitmap(w, h, Config.RGB_565);
bitmap.setPixels(rawData,
0
, w,
0
,
0
, w, h);
return
bitmap;
}
|
2.源码分析白边的生成过程
下面就分析Zxing的源码以及默认白边的形成
先看generateQRCode里的关键方法MultiFormatWriter类的encode方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
public
BitMatrix encode(String contents, BarcodeFormat format,
int
width,
int
height, Map hints)
throws
WriterException {
Writer writer;
switch
(format) {
case
EAN_8:
writer =
new
EAN8Writer();
break
;
case
EAN_13:
writer =
new
EAN13Writer();
break
;
case
UPC_A:
writer =
new
UPCAWriter();
break
;
case
QR_CODE:
|