編輯:關於 Android 程式設計
ZXing 是 Google 開源的一款「多格式二維碼處理」庫,既能生成二維碼,也能掃描識別二維碼。本文聚焦其中的第一部分——如何用它生成帶 Logo 的二維碼。
先看效果圖:

ZXing 官方各版本的相關文件可從 GitHub 下載:https://github.com/zxing/zxing/releases。本文示例使用的 jar 包版本為 3.2.0。
我們先封裝一個 QRCodeUtil 工具類,把生成二維碼與疊加 Logo 的邏輯都收攏其中:
/**
* 二維碼生成工具類
*/
public class QRCodeUtil {
/**
* 生成二維碼 Bitmap
*
* @param content 內容
* @param widthPix 圖片寬度
* @param heightPix 圖片高度
* @param logoBm 二維碼中心的 Logo 圖標(可為 null)
* @param filePath 二維碼圖片的存儲路徑
* @return 生成並保存是否成功
*/
public static boolean createQRImage(String content, int widthPix, int heightPix,
Bitmap logoBm, String filePath) {
try {
if (content == null || "".equals(content)) {
return false;
}
// 配置參數
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 字符集
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 容錯級別
// 設置空白邊距,默認為 4
// hints.put(EncodeHintType.MARGIN, 2);
// 圖像數據轉換,使用矩陣轉換
BitMatrix bitMatrix = new QRCodeWriter().encode(
content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
int[] pixels = new int[widthPix * heightPix];
// 按照二維碼算法,逐個生成圖片的像素
for (int y = 0; y < heightPix; y++) {
for (int x = 0; x < widthPix; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = 0xff000000;
} else {
pixels[y * widthPix + x] = 0xffffffff;
}
}
}
// 使用 ARGB_8888 格式生成二維碼圖片
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
if (logoBm != null) {
bitmap = addLogo(bitmap, logoBm);
}
// 必須用 compress 壓縮後再保存,直接返回未壓縮的 bitmap 內存消耗巨大
return bitmap != null &&
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filePath));
} catch (WriterException | IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 在二維碼中間添加 Logo 圖案
*/
private static Bitmap addLogo(Bitmap src, Bitmap logo) {
if (src == null) {
return null;
}
if (logo == null) {
return src;
}
int srcWidth = src.getWidth();
int srcHeight = src.getHeight();
int logoWidth = logo.getWidth();
int logoHeight = logo.getHeight();
if (srcWidth == 0 || srcHeight == 0) {
return null;
}
if (logoWidth == 0 || logoHeight == 0) {
return src;
}
// logo 大小為二維碼整體的 1/5
float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
try {
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(src, 0, 0, null);
canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
} catch (Exception e) {
bitmap = null;
e.getStackTrace();
}
return bitmap;
}
}
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText contentET = (EditText) findViewById(R.id.create_qr_content); // 輸入內容
final ImageView imageView = (ImageView) findViewById(R.id.create_qr_iv); // 顯示二維碼
final CheckBox addLogoCB = (CheckBox) findViewById(R.id.create_qr_addLogo); // 是否加 Logo
Button createQrBtn = (Button) findViewById(R.id.create_qr_btn);
createQrBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String filePath = getFileRoot(MainActivity.this) + File.separator
+ "qr_" + System.currentTimeMillis() + ".jpg";
// 二維碼較大時,生成與保存較耗時,放到子線程執行
new Thread(new Runnable() {
@Override
public void run() {
boolean success = QRCodeUtil.createQRImage(
contentET.getText().toString().trim(), 800, 800,
addLogoCB.isChecked()
? BitmapFactory.decodeResource(getResources(), R.mipmap.qr_logo)
: null,
filePath);
if (success) {
runOnUiThread(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(BitmapFactory.decodeFile(filePath));
}
});
}
}
}).start();
}
});
}
// 文件存儲根目錄
private String getFileRoot(Context context) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File external = context.getExternalFilesDir(null);
if (external != null) {
return external.getAbsolutePath();
}
}
return context.getFilesDir().getAbsolutePath();
}
}
本示例把圖片保存在 context.getExternalFilesDir(null) 目錄下。按照官方 API 文檔,從 KitKat(Android 4.4)開始,把文件寫入這個目錄將不再需要 SD 卡讀寫權限。但實測發現:紅米 Note 與魅族 MX3(均為 Android 4.4.4)確實無須申請權限;而在我的華為 P6(Android 4.4.2)上,卻必須聲明權限才能成功寫入,也就是要在 manifest 中加上:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
由此我個人推測:所謂「無須權限」,很可能是從 Android 4.4.4 才真正開始的。大家在實際開發中,面對不同廠商、不同版本的 ROM,還是以真實測試結果為準。
Android 加載對話框與異步執行同步實現方法
在 Android 中,透過子線程連接網路取得資料的同時,往往需要顯示一個加載進度對話框給使用者。這個功能需要 Thread 與 Handler 搭配完成:在 Threa
Android 繪圖 API 總整理:Bitmap、Canvas、Paint、Path 一次搞懂
只要做過自訂控制項,就一定會跟這幾個傢伙打照面:Bitmap 負責裝圖,Canvas 負責畫布,Paint 負責畫筆,Path 負責軌跡。Android 在這塊提供的支援
ListView 異步載入與圖片緩存實踐
需求說明 本範例示範如何從網路異步取得文字與圖片資料,並顯示在 ListView 中。同時,透過記憶體緩存保存已下載的圖片,避免重複請求,提升列表滾動的流暢度。 佈局
Android 多線程:IntentService 完全詳解
上一篇聊了 HandlerThread,本篇就來看看它在 IntentService 中的實際應用。閱讀前建議先了解 HandlerThread,有助於更好地掌握 Int