1.導入Zxing
implementation 'com.google.zxing:core:3.4.1'
2.製作甚麼樣式的Barcode
private fun barcodeFormatCode(content: String): Bitmap {
//選擇輸出類型
val barcode = BarcodeFormat.QR_CODE
val matrix = MultiFormatWriter().encode(content, barcode, 600, 600, null)
return matrix2Bitmap(matrix)
}
3.設置Barcode內部屬性
private fun matrix2Bitmap(matrix: BitMatrix): Bitmap {
val w = matrix.width
val h = matrix.height
val rawData = IntArray(w * h)
for (i in 0 until w) {
for (j in 0 until h) {
//沒內容的顏色
var color = Color.YELLOW
if (matrix.get(i, j)) {
//有內容的顏色
color = Color.BLUE
}
rawData[i + (j * w)] = color
}
}
val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
bitmap.setPixels(rawData, 0, w, 0, 0, w, h)
return bitmap
}
4.調用方法生成
code.setImageBitmap(barcodeFormatCode("QR-Code"))
5.效果展示