Search code examples
androidbitmapzxingqr-code

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


I'm using in my app ZXing library for generating QR code. I want to generated QR code that should fits to the width of the screen (maybe some small padding).

If I set width of the screen as width size of QR code I get smaller QR code. Look at the screenshot (it's 320x240 resolution). I want QR code to fit the black area. Why is QR code in red so small?

How do I stretch it to the black area?

From the app

My code:

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);

Generating QR code:

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;
}

Solution

  • I find a problem!

    This line:

     String encoding = guessAppropriateEncoding(contentsToEncode);
    

    returns null

    So It doesn´t set

    EncodeHintType.MARGIN. 
    

    Remove the codition and it should be ok.

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