現(xiàn)在二維碼已經(jīng)成了人們生活中的一部分,各種角落、超市、還是小店門(mén)口,亦或是商品包裝上都少不了它,也可見(jiàn)它帶給人們的便利。好了,廢話(huà)有點(diǎn)多,本文章主要想說(shuō)一下在客戶(hù)端展示二維碼的實(shí)現(xiàn)。
一般就是兩種方法:
- 服務(wù)端生成二維碼圖片,客戶(hù)端去獲取圖片。
- 客戶(hù)端自己生成二維碼。
我這里就只講客戶(hù)端自己生成二維碼的步驟:
- 導(dǎo)入zxing的核心類(lèi)庫(kù),鏈接地址:http://pan.baidu.com/s/1qYTR0SW
- 生成二維碼圖片。
導(dǎo)入zxing的核心類(lèi)庫(kù)
因?yàn)橹皇菍?shí)現(xiàn)生成二維碼的功能,并不需要把整個(gè)zxing的項(xiàng)目去拷貝下來(lái)(如果用到掃描解析二維碼,還需要將官方的項(xiàng)目工程拷貝下來(lái)),只需要將核心類(lèi)庫(kù)的包導(dǎo)入到你的項(xiàng)目中即可。
生成二維碼圖片
public void createImage(String codeFormat, ImageView codeImg) {
try {
if (codeFormat == null || "".equals(codeFormat) || codeFormat.length() < 1) {
return;
}
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix bitMatrix = new QRCodeWriter().encode(codeFormat, 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;
}
}
}
Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
codeImg.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
二維碼的寬度和高度可以根據(jù)自己的需求自己定義,codeFormat就是你想要存儲(chǔ)在二維碼中的字符串信息(注意二維碼容量是有限制的,里面的信息盡量小一點(diǎn),更有利于解析)。
哈哈是不是很簡(jiǎn)單呢O(∩_∩)O哈哈