java 使用zxing生成二维码,要求二维码上面生成可换行标题
时间: 2024-03-26 16:40:39 浏览: 118
java用zxing生成二维码
可以使用zxing提供的MultiFormatWriter类来生成二维码。要在二维码上方生成可换行标题,可以使用Bitmap.createBitmap()方法创建一个新的Bitmap对象,并在上面绘制标题和二维码。具体代码如下:
```java
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
public class QRCodeUtil {
/**
* 生成带有标题的二维码
*
* @param content 二维码内容
* @param title 标题
* @param width 二维码宽度
* @param height 二维码高度
* @return 带有标题的二维码Bitmap对象
*/
public static Bitmap createQRCodeWithTitle(String content, String title, int width, int height) {
try {
// 生成二维码矩阵
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height);
// 获取二维码图片的宽高
int qrCodeWidth = bitMatrix.getWidth();
int qrCodeHeight = bitMatrix.getHeight();
// 新建一个Bitmap对象
Bitmap bitmap = Bitmap.createBitmap(qrCodeWidth, qrCodeHeight + 50, Bitmap.Config.ARGB_8888);
// 在Bitmap上绘制标题和二维码
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextSize(30);
paint.setColor(0xff000000);
Rect bounds = new Rect();
paint.getTextBounds(title, 0, title.length(), bounds);
int titleHeight = bounds.height();
canvas.drawText(title, (qrCodeWidth - bounds.width()) / 2f, titleHeight, paint);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix qrCodeMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeWidth, qrCodeHeight);
int[] qrCodePixels = new int[qrCodeWidth * qrCodeHeight];
for (int y = 0; y < qrCodeHeight; y++) {
int offset = y * qrCodeWidth;
for (int x = 0; x < qrCodeWidth; x++) {
qrCodePixels[offset + x] = bitMatrix.get(x, y) ? 0xff000000 : 0xffffffff;
}
}
bitmap.setPixels(qrCodePixels, 0, qrCodeWidth, 0, titleHeight + 10, qrCodeWidth, qrCodeHeight);
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
return null;
}
}
}
```
调用方式:
```java
Bitmap bitmap = QRCodeUtil.createQRCodeWithTitle("二维码内容", "标题\n换行", 400, 400);
imageView.setImageBitmap(bitmap);
```
阅读全文