Android Generate Text to QR Code
2 min readApr 7, 2023
I had develop and app for scan qr code but it seen like we need and qr generator right? It will work either compose or not. That’s not a problem.
If you want to know more here my site
So here we are .
Firstly you need implement another dependency call Zxing
implementation("com.google.zxing:core:3.4.1")
and just a simple function it show do the magic.
What we need is image as bitmap so
fun qrCodeGenerator(data: String, size: Int) = try {
val writer = QRCodeWriter()
val bitMatrix: BitMatrix = writer.encode(data, BarcodeFormat.QR_CODE, size, size)
val width: Int = bitMatrix.width
val height: Int = bitMatrix.height
val pixels = IntArray(width * height)
for (y in 0 until height) {
val offset = y * width
for (x in 0 until width) {
pixels[offset + x] =
if (bitMatrix.get(x, y)) 0xFF000000.toInt() else 0xFFFFFFFF.toInt()
}
}
Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).apply {
setPixels(pixels, 0, width, 0, 0, width, height)
}
} catch (e: Exception) {
null
}
For Jetpack Compose
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val qr = qrCodeGenerator("http://128.199.87.161/", 200)
if (qr != null)
Image(
bitmap = qr.asImageBitmap(),
contentDescription = "my site",
contentScale = ContentScale.Fit,
)
}
For None Compose.
qrCodeGenerator("http://128.199.87.161/", size = 500)?.let { bitmap ->
binding.imageView.setImageBitmap(bitmap)
}
Thank you for your time
I hope this is what you looking for.