Android:使用Zxing生成的二维码有边距(不适合该区域)

Android: Generated QR code using Zxing has margins (is not fit to the area)

我在我的应用程序中使用 ZXing 库来生成二维码。我想生成适合屏幕宽度的 QR 码(可能是一些小填充)。

如果我将屏幕的宽度设置为二维码的宽度尺寸,我会得到更小的二维码。查看屏幕截图(分辨率为 320x240)。我想要二维码适合黑色区域。为什么红色的二维码这么小?

如何拉伸到黑色区域?

我的代码:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x; 

Bitmap bm = encodeAsBitmap(mGeneratedURL, BarcodeFormat.QR_CODE, width, width);
qrcodeImage.setImageBitmap(bm);

生成二维码:

private Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
    String contentsToEncode = contents;
    if (contentsToEncode == null) {
        return null;
    }
    Map<EncodeHintType, Object> hints = null;
    String encoding = guessAppropriateEncoding(contentsToEncode);
    if (encoding != null) {
        hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
        //hints.put(EncodeHintType.CHARACTER_SET, encoding);
        hints.put(EncodeHintType.MARGIN, 0); /* default = 4 */
    }
    MultiFormatWriter writer = new MultiFormatWriter();
    BitMatrix result;
    try {
        result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
    } catch (IllegalArgumentException iae) {
        // Unsupported format
        return null;
    }

    int width = result.getWidth();
    int height = result.getHeight();
    int[] pixels = new int[width * height];
    for (int y = 0; y < height; y++) {
        int offset = y * width;
        for (int x = 0; x < width; x++) {
            pixels[offset + x] = result.get(x, y) ? RED : Color.BLACK;
        }
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height,
            Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
}

我发现了一个问题!

这一行:

 String encoding = guessAppropriateEncoding(contentsToEncode);

returns 空

所以它没有设置

EncodeHintType.MARGIN. 

去掉编码应该就可以了

//if (encoding != null) {
    hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
    //hints.put(EncodeHintType.CHARACTER_SET, encoding);
    hints.put(EncodeHintType.MARGIN, 0); /* default = 4 */
//}