android 生成二维码
时间: 2023-07-28 14:51:49 浏览: 70
在 Android 上生成二维码可以使用 Google 提供的 ZXing 库,这是一款开源的条码/二维码扫描库,也支持生成二维码。下面是一个简单的示例:
1. 在 app 的 build.gradle 文件中添加以下依赖:
```
dependencies {
implementation 'com.google.zxing:core:3.3.3'
}
```
2. 在需要生成二维码的地方,创建一个 BitMatrix 对象,并使用 QRCodeWriter 将内容转换为二维码矩阵,然后使用 MatrixToImageWriter 将矩阵转换为 Bitmap 图片:
```
String content = "这是一个测试二维码";
int width = 500, height = 500;
QRCodeWriter writer = new QRCodeWriter();
try {
BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height);
int matrixWidth = bitMatrix.getWidth();
Bitmap bmp = Bitmap.createBitmap(matrixWidth, matrixWidth, Bitmap.Config.RGB_565);
for (int x = 0; x < matrixWidth; x++) {
for (int y = 0; y < matrixWidth; y++) {
bmp.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
}
}
ImageView imageView = findViewById(R.id.image_view);
imageView.setImageBitmap(bmp);
} catch (WriterException e) {
e.printStackTrace();
}
```
上面的代码中,content 是要转换为二维码的内容,width 和 height 是二维码图片的宽度和高度,QRCodeWriter 是生成二维码的类。最后将生成的 Bitmap 设置到 ImageView 中即可。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)