Last active
July 4, 2024 10:45
-
-
Save dev-niiaddy/8f936062291e3d328c7d10bb644273d0 to your computer and use it in GitHub Desktop.
A function to encode text as a QR code using BitmapPainter and zxing-core for use in jetpack compose with Image composable.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Composable | |
fun rememberQrBitmapPainter( | |
content: String, | |
size: Dp = 150.dp, | |
padding: Dp = 0.dp | |
): BitmapPainter { | |
val density = LocalDensity.current | |
val sizePx = with(density) { size.roundToPx() } | |
val paddingPx = with(density) { padding.roundToPx() } | |
var bitmap by remember(content) { | |
mutableStateOf<Bitmap?>(null) | |
} | |
LaunchedEffect(bitmap) { | |
if (bitmap != null) return@LaunchedEffect | |
launch(Dispatchers.IO) { | |
val qrCodeWriter = QRCodeWriter() | |
val encodeHints = mutableMapOf<EncodeHintType, Any?>() | |
.apply { | |
this[EncodeHintType.MARGIN] = paddingPx | |
} | |
val bitmapMatrix = try { | |
qrCodeWriter.encode( | |
content, BarcodeFormat.QR_CODE, | |
sizePx, sizePx, encodeHints | |
) | |
} catch (ex: WriterException) { | |
null | |
} | |
val matrixWidth = bitmapMatrix?.width ?: sizePx | |
val matrixHeight = bitmapMatrix?.height ?: sizePx | |
val newBitmap = Bitmap.createBitmap( | |
bitmapMatrix?.width ?: sizePx, | |
bitmapMatrix?.height ?: sizePx, | |
Bitmap.Config.ARGB_8888, | |
) | |
for (x in 0 until matrixWidth) { | |
for (y in 0 until matrixHeight) { | |
val shouldColorPixel = bitmapMatrix?.get(x, y) ?: false | |
val pixelColor = if (shouldColorPixel) Color.BLACK else Color.WHITE | |
newBitmap.setPixel(x, y, pixelColor) | |
} | |
} | |
bitmap = newBitmap | |
} | |
} | |
return remember(bitmap) { | |
val currentBitmap = bitmap ?: Bitmap.createBitmap( | |
sizePx, sizePx, | |
Bitmap.Config.ARGB_8888, | |
).apply { eraseColor(Color.TRANSPARENT) } | |
BitmapPainter(currentBitmap.asImageBitmap()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this gist! I forked to provide an Image Composable with circular indicator while the QR code renders.
It also includes the import statements and the performance enhancement from @SherifMuSherif.
https://gist.github.com/ryanholden8/6e921a4dc2a40bd40b3b5a15aaff4705