//生成二维码方法
suspend fun createQRCode(dataStr: String,size: Int):Bitmap? = withContext(Dispatchers.IO) {
val hashTable = Hashtable<EncodeHintType,Any>()
hashTable[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.L
hashTable[EncodeHintType.CHARACTER_SET] = "UTF-8"
hashTable[EncodeHintType.MARGIN] = 0
var mutableFormatWriter = MultiFormatWriter().encode(dataStr,BarcodeFormat.QR_CODE,size,size,hashTable)
//去掉白边
mutableFormatWriter = deleteWhite(mutableFormatWriter)
val width = mutableFormatWriter.width
val height = mutableFormatWriter.height
val pixels = IntArray(width * height)
for (y in 0 until height){
for (x in 0 until width){
if (mutableFormatWriter[x,y]){
pixels[y * height + x] =Color.BLACK
}else{
pixels[y * height + x] = Color.WHITE
}
}
}
val bitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888)
bitmap.setPixels(pixels,0,width,0,0,width,height)
return@withContext bitmap
}
//读取二维码区域重新生成一个BitMatrix
private fun deleteWhite(matrix: BitMatrix): BitMatrix{
val rec = matrix.enclosingRectangle //检测“纯”二维码码的封闭矩形
val resWidth = rec[2] + 1 //宽
val resHeight = rec[3] + 1 //高
val resMatrix = BitMatrix(resWidth,resHeight)
resMatrix.clear()
for (i in 0 until resWidth){
for (j in 0 until resHeight){
if (matrix.get(i + rec[0], j + rec[1]))
resMatrix.set(i,j)
}
}
return resMatrix
}