Android - ZXing 库生成二维码

⑧说了,直接进入主题

引用 ZXing 库

在 build.gradle 中添加引用

1
implementation 'com.google.zxing:core:3.4.0'

操作类 QRUtil

新建 QRUtil.java 操作类

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
public class QRUtil {
/**
* 生成二维码
* @param content 二维码内容
* @param width 宽度
* @param height 高度
* @param logo 图标
* @return Bitmap
*/
public static Bitmap createQRImage(String content, int width, int height, Bitmap logo) {
try {
if (content == null || "".equals(content)) {
return null;
}
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN, 1);

BitMatrix bitMatrix = null;
try {
bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
} catch (WriterException e) {
e.printStackTrace();
}
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * width + x] = 0xff000000;
} else {
pixels[y * width + x] = 0xffffffff;
}
}
}

Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

if (logo != null) {
bitmap = addLogo(bitmap, logo);
}
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 向二维码中心添加图标
* @param src 原(二维码)图
* @param logo 图标 Bitmap
* @return Bitmap
*/
private static Bitmap addLogo(Bitmap src, Bitmap logo) {
if (src == null) {
return null;
}

if (logo == null) {
return src;
}

int srcWidth = src.getWidth();
int srcHeight = src.getHeight();
int logoWidth = logo.getWidth();
int logoHeight = logo.getHeight();

if (srcWidth == 0 || srcHeight == 0) {
return null;
}

if (logoWidth == 0 || logoHeight == 0) {
return src;
}

float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
try {
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(src, 0, 0, null);
canvas.scale(scaleFactor, scaleFactor, srcWidth / (float) 2, srcHeight / (float) 2);
canvas.drawBitmap(logo, (srcWidth - logoWidth) / (float) 2, (srcHeight - logoHeight) / (float) 2, null);
canvas.save();
canvas.restore();
} catch (Exception e) {
bitmap = null;
e.getStackTrace();
}

return bitmap;
}
}

使用 Demo

activity_main.xml

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
37
38
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
tools:ignore="HardcodedText">


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">

<EditText
android:id="@+id/et_content"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:ems="10"
android:hint="内容"
android:inputType="textPersonName" />

<Button
android:id="@+id/btn_pick_icon"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="选择图标" />
</LinearLayout>

<ImageView
android:id="@+id/iv_qr"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

MainActivity.java

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {

private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE"
};

private ImageView iv_qr;
private EditText et_content;

private int PICK_RESULT_CODE = 1;

private Bitmap logoBM = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
int permission = ActivityCompat.checkSelfPermission(MainActivity.this, "android.permission.WRITE_EXTERNAL_STORAGE");
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
}
} catch (Exception e) {
e.printStackTrace();
}

iv_qr = findViewById(R.id.iv_qr);
et_content = findViewById(R.id.et_content);
et_content.addTextChangedListener(this);

findViewById(R.id.btn_pick_icon).setOnClickListener(this);
}

public void enableChanges() {
int devWid = getResources().getDisplayMetrics().widthPixels;
iv_qr.setImageBitmap(QRUtil.createQRImage(et_content.getText().toString(), devWid, devWid, logoBM));
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_pick_icon:
Intent PickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(PickIntent, PICK_RESULT_CODE);
break;
}
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
enableChanges();
}

@Override
public void afterTextChanged(Editable s) {

}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_RESULT_CODE && resultCode == RESULT_OK && null != data) {
String imagePath = null;
Uri uri = data.getData();
String[] project = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, project, null, null, null);
assert cursor != null;
if (cursor.moveToFirst()) {
;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
imagePath = cursor.getString(column_index);
}
cursor.close();
logoBM = BitmapFactory.decodeFile(imagePath);
enableChanges();
}
}
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×