1.先導入函示庫(build.gradle: Module)
dependencies {
implementation 'com.contrarywind:Android-PickerView:4.1.9'
}
2.設定條碼格式以及大小
private fun barcodeFormatCode(num: String) : Bitmap {
val barcode = BarcodeFormat.CODE_128
val matrix = MultiFormatWriter().encode(num, barcode, 800, 160, null)
return bitMatrixToBitmap(matrix)
}
3.創建條碼的圖片
private fun bitMatrixToBitmap(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.WHITE;
if (matrix.get(i, j)) {
// 有内容的部分,颜色设置为黑色,可以自己修改成其他颜色
color = Color.BLACK;
}
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;
}
5.調用方法並設置到ImageView上
barcode.setImageBitmap(barcodeFormatCode("123123"))
6.效果展示