首先需要导入依赖
在build.gradle中导入依赖
implementation 'com.google.zxing:core:3.3.0'
编写工具类,生成二维码
class UrlToQR {
companion object{
fun createQRCodeBitmap(
content: String,
width: Int,
height: Int,
characterSet: String = "UTF-8",
errorCorrectionLevel: String = "M",
margin: String = "1",
colorBlack: Int = 0xFF000000.toInt(),
colorWhite: Int = 0xFFFFFFFF.toInt()
): Bitmap? {
// 字符串内容判空
if (content.isBlank()) return null
// 宽和高>=0
if (width < 0 || height < 0) return null
return try {
/** 1.设置二维码相关配置 */
val hints = hashMapOf<EncodeHintType, Any>()
// 字符转码格式设置
if (characterSet.isNotBlank()) {
hints[EncodeHintType.CHARACTER_SET] = characterSet
}
// 容错率设置
if (errorCorrectionLevel.isNotBlank()) {
hints[EncodeHintType.ERROR_CORRECTION] = errorCorrectionLevel
}
// 空白边距设置
if (margin.isNotBlank()) {
hints[EncodeHintType.MARGIN] = margin
}
/** 2.将配置参数传入到QRCodeWriter的encode方法生成BitMatrix(位矩阵)对象 */
val bitMatrix = QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints)
/** 3.创建像素数组,并根据BitMatrix(位矩阵)对象为数组元素赋颜色值 */
val pixels = IntArray(width * height)
for (y in 0 until height) {
for (x in 0 until width) {
// bitMatrix.get(x,y)方法返回true是黑色色块,false是白色色块
pixels[y * width + x] = if (bitMatrix[x, y]) colorBlack else colorWhite
}
}
/** 4.创建Bitmap对象,根据像素数组设置Bitmap每个像素点的颜色值,并返回Bitmap对象 */
Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).apply {
setPixels(pixels, 0, width, 0, 0, width, height)
return this
}
} catch (e: WriterException) {
e.printStackTrace()
null
}
}
}
}
最后调用函数,生成bitmap,可以使用image的 setImageBitmap() 直接使用:
UrlToQR.createQRCodeBitmap(
"http://www.baidu.com",
800,
800,
"UTF-8",
"H",
"1",
Color.BLACK,
Color.WHITE)
这里是将链接转换成了二维码,扫描二维码后可以直接进入链接