此次專案目的是產生Qr Code如下圖所示:

 

首先QR Code 產生可以視為一個演算法,因此在此建構一個專門產生QR Code圖片的物件。

輸入字串後產生QR Code 圖像。

public class QrcodeMaker {
    private static final int WIDTH = 1000;
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    public static Bitmap encodeAsBitmap(String str) throws WriterException {
        BitMatrix result;
        try {
            result = new MultiFormatWriter().encode(str,BarcodeFormat.QR_CODE, WIDTH, WIDTH,getHitnts());
        } catch (IllegalArgumentException iae) {
            // Unsupported format
            return null;
        }
        int w = result.getWidth();
        int h = result.getHeight();
        int[] pixels = new int[w * h];
        for (int y = 0; y < h; y++) {
            int offset = y * w;
            for (int x = 0; x < w; x++) {
                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, WIDTH, 0, 0, w, h);
        return bitmap;
    }

    private static Map<EncodeHintType,String> getHitnts(){
        Map<EncodeHintType,String> hints = new TreeMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        return  hints;
    }
}

 

使用方法如下 :

public void BuildQR(String str){
    try {
        Bitmap bitmap = QrcodeMaker.encodeAsBitmap(str);
        imageView.setImageBitmap(bitmap);
    } catch (WriterException e) {
        e.printStackTrace();
        Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
    }
}
arrow
arrow
    文章標籤
    Android
    全站熱搜

    Lung-Yu,Tsai 發表在 痞客邦 留言(0) 人氣()