您可以使用 Zxing library 在您的设备上生成二维码。这与 Android 上的 Charm Down BarcodeScan 服务使用的库相同。
首先,将此依赖项添加到您的构建中:
compile 'com.google.zxing:core:3.3.3'
现在您可以将设备服务与 QR 生成器结合起来检索 UUID。
获得 zxing 格式的 QR 后,您需要生成图像或文件。
鉴于您无法在 Android/iOS 上使用 Swing,您必须避免使用 MatrixToImageWriter,并根据生成的像素手动执行。
类似这样的:
public Image generateQR(int width, int height) {
String uuid = Services.get(DeviceService.class)
.map(DeviceService::getUuid)
.orElse("123456789"); // <--- for testing on desktop
QRCodeWriter qrCodeWriter = new QRCodeWriter();
try {
BitMatrix bitMatrix = qrCodeWriter.encode(uuid, BarcodeFormat.QR_CODE, width, height);
WritablePixelFormat<IntBuffer> wf = PixelFormat.getIntArgbInstance();
WritableImage writableImage = new WritableImage(width, height);
PixelWriter pixelWriter = writableImage.getPixelWriter();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
pixelWriter.setColor(x, y, bitMatrix.get(x, y) ?
Color.BLACK : Color.WHITE);
}
}
return writableImage;
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
现在您可以在视图中调用此方法,添加ImageView 来渲染生成的图像:
ImageView imageView = new ImageView();
imageView.setFitWidth(256);
imageView.setFitHeight(256);
imageView.setImage(service.generateQR(256, 256));
编辑
如果您想生成二维码或条形码,您可以将上面generateQR中的代码替换为:
MultiFormatWriter codeWriter = new MultiFormatWriter();
BitMatrix bitMatrix = codeWriter.encode(uuid, format, width, height);
...
并将参数设置为:
- 二维码:
BarcodeFormat.QR_CODE,并使用正方形大小,如 256x 256
- 对于条形码:
BarcodeFormat.CODE_128,并使用 256 x 64 等矩形尺寸