How to generate QR Code or Bar Code by using Gluon mobile in order to support multi-platorm?

血红的双手。 提交于 2020-01-06 05:57:04

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/54445369/how-to-generate-qr-code-or-bar-code-by-using-gluon-mobile-in-order-to-support-mu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!