如何使用Zxing缩短生成QR码的时间

时间:2017-05-03 07:59:24

标签: android qr-code

我正在使用QR条形码创建应用。条形码正确加载,但不知怎的,加载有点慢,点击菜单后约3-5秒。

我们可以加快速度吗?或者页面加载那么长吗?其他部分加载仅需1秒或更短时间。该应用程序也离线,因此无需连接互联网。

这里是我生成QR条码的代码:

ImageView imageViewBarcode = (ImageView)findViewById(R.id.imageViewBarcode);

    try {
        bitmap = TextToImageEncode(barcode_user);

        imageViewBarcode.setImageBitmap(bitmap);

    } catch (WriterException e) {
        e.printStackTrace();
    }

上面的代码放在onCreate中。因此,当页面加载时,它会生成条形码。

这里是创建条形码的功能

Bitmap TextToImageEncode(String Value) throws WriterException {
    BitMatrix bitMatrix;
    try {
        bitMatrix = new MultiFormatWriter().encode(
                Value,
                BarcodeFormat.DATA_MATRIX.QR_CODE,
                QRcodeWidth, QRcodeWidth, null
        );

    } catch (IllegalArgumentException Illegalargumentexception) {

        return null;
    }
    int bitMatrixWidth = bitMatrix.getWidth();

    int bitMatrixHeight = bitMatrix.getHeight();

    int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];

    for (int y = 0; y < bitMatrixHeight; y++) {
        int offset = y * bitMatrixWidth;

        for (int x = 0; x < bitMatrixWidth; x++) {

            pixels[offset + x] = bitMatrix.get(x, y) ?
                    getResources().getColor(R.color.colorBlack):getResources().getColor(R.color.colorWhite);
        }
    }
    Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);

    bitmap.setPixels(pixels, 0, 500, 0, 0, bitMatrixWidth, bitMatrixHeight);
    return bitmap;
}

2 个答案:

答案 0 :(得分:8)

你在双循环中调用getResources()。getColor() - 即当你的图像大小为100 * 100像素时,这将被调用10000次。而是将颜色值分配给循环外部的某些变量,并在循环内使用这些变量。

int color_black = getResources().getColor(R.color.colorBlack);
int color_white = getResources().getColor(R.color.colorWhite);

for (int y = 0; y < bitMatrixHeight; y++) {
    int offset = y * bitMatrixWidth;

    for (int x = 0; x < bitMatrixWidth; x++) {
        pixels[offset + x] = bitMatrix.get(x, y) ? color_black : color_white;
    }
}

编辑:添加代码示例

答案 1 :(得分:0)

在另一个帖子上找到了这个:zxing generate QR。解决了类似的问题。