Now I would like to generate QR Code dynamically from the UUID from the device. I am wonder how to do it in order to support multi-platform in gluon? Please also recommended me If I simplfy using normall java library or special lib which developed by gluon Team.
-
So you want to generate a QR on your mobile app for a given string, so you can then read it from another mobile app using the BarcodeService? – José Pereda Jan 30 '19 at 16:54
-
Yes, my application will automatic generate QRCode or BarCode base on UUID then show it as image. That QRCode will be use later by scanner. – Sovandara LENG Jan 30 '19 at 16:57
1 Answers
You can use the Zxing library to generate the QR on your device. This is the same library that is used by the Charm Down BarcodeScan service on Android.
First of all, add this dependency to your build:
compile 'com.google.zxing:core:3.3.3'
Now you can combine the Device service to retrieve the UUID with the QR generator.
Once you have the QR in zxing format, you will need to either generate an image or a file.
Given that you can't use Swing on Android/iOS, you have to avoid MatrixToImageWriter
, and do it manually, based on the generated pixels.
Something like this:
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;
}
Now you can call this method from your view, adding an ImageView
to render the generated image:
ImageView imageView = new ImageView();
imageView.setFitWidth(256);
imageView.setFitHeight(256);
imageView.setImage(service.generateQR(256, 256));
EDIT
If you want to generate either a QR code or a barcode, you can replace the above code in generateQR
with this:
MultiFormatWriter codeWriter = new MultiFormatWriter();
BitMatrix bitMatrix = codeWriter.encode(uuid, format, width, height);
...
and set an argument with the format to:
- For QR code:
BarcodeFormat.QR_CODE
, and use square size like 256x 256 - For Barcode:
BarcodeFormat.CODE_128
, and use rectangular size like 256 x 64

- 44,311
- 7
- 104
- 132
-
-
Yes, I plan to put two option for the app. So user can switch between BarCode and QR. It depending on the requirement. – Sovandara LENG Jan 31 '19 at 09:56