Android 二維碼快速生成代碼

<pre name="code" class="java">看了很多人在找關於二維碼生成的代碼 今天就抽時間寫了一下,希望對大家有所幫助!
<a target=_blank href="http://download.csdn.net/download/u012974916/8197269" target="_blank">點擊打開鏈接</a>
public class MainActivity extends Activity {
    
    private static final String TAG=MainActivity.class.getSimpleName();
    private TextView qr_text;
    private ImageView qr_image;
    
    private final int QR_WIDTH=140;
    private final int QR_HEIGHT=140;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        qr_text=(TextView) findViewById(R.id.textView1);
        qr_image=(ImageView) findViewById(R.id.imageView1);
        createImage();
    }


 // 生成QR圖
    private void createImage() {
        try {
            // 需要引入core包
            QRCodeWriter writer = new QRCodeWriter();


            String text = qr_text.getText().toString();
            text="黃明明";
            Log.i(TAG, "生成的文本:" + text);
            if (text == null || "".equals(text) || text.length() < 1) {
                return;
            }


            // 把輸入的文本轉爲二維碼
            BitMatrix martix = writer.encode(text, BarcodeFormat.QR_CODE,
                    QR_WIDTH, QR_HEIGHT);


            System.out.println("w:" + martix.getWidth() + "h:"
                    + martix.getHeight());


            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = new QRCodeWriter().encode(text,
                    BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
            for (int y = 0; y < QR_HEIGHT; y++) {
                for (int x = 0; x < QR_WIDTH; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * QR_WIDTH + x] = 0xff000000;
                    } else {
                        pixels[y * QR_WIDTH + x] = 0xffffffff;
                    }


                }
            }


            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
                    Bitmap.Config.ARGB_8888);


            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
            qr_image.setImageBitmap(bitmap);


        } catch (WriterException e) {
            e.printStackTrace();
        }
    }
}
佈局文件記得自己寫哦哦!!!
http://download.csdn.net/download/u012974916/8197269


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章