前言
在 Jetpack Compose 中加载 Bitmap 到 Image 组件非常直接,你可以使用 asImageBitmap() 扩展函数将 Bitmap 转换为 Compose 可识别的 ImageBitmap 类型,然后通过 Image 组件显示。
asImageBitmap() 是一个轻量级转换函数,它并没有对原始 Bitmap 进行像素级复制或处理,而是通过包装原生 Bitmap 生成一个 ImageBitmap 引用(可以理解为「视图层的包装」)。
这个过程主要是建立 Compose 绘图系统与 Android 原生 Bitmap 的关联,执行时间通常在毫秒级以下,因此在主线程执行一般不会导致界面卡顿。
添加依赖
1 2 3
| dependencies { implementation("com.journeyapps:zxing-android-embedded:4.2.0") }
|
获取二维码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import android.graphics.Bitmap import android.graphics.Color import com.google.zxing.BarcodeFormat import com.google.zxing.WriterException import com.google.zxing.qrcode.QRCodeWriter import androidx.core.graphics.createBitmap import androidx.core.graphics.set
object ZQRCodeUtils { fun generateQRCode(text: String): Bitmap? { val writer = QRCodeWriter() try { val bitMatrix = writer.encode(text, BarcodeFormat.QR_CODE, 512, 512) val width = bitMatrix.getWidth() val height = bitMatrix.getHeight() val bmp = createBitmap(width, height, Bitmap.Config.RGB_565) for (x in 0..<width) { for (y in 0..<height) { bmp[x, y] = if (bitMatrix.get(x, y)) Color.BLACK else Color.WHITE } } return bmp } catch (e: WriterException) { e.printStackTrace() return null } } }
|
展示
1 2 3 4 5 6 7 8 9 10 11 12
| @Composable fun ZImgLocalBitmap(bitmap: Bitmap) { val imageBitmap = bitmap.asImageBitmap() Image( bitmap = imageBitmap, contentDescription = null, modifier = Modifier .fillMaxSize(), contentScale = ContentScale.FillBounds ) }
|
VM
1 2 3 4 5
| val qrCodeBitmap = mutableStateOf<Bitmap?>(null) val url = CommonData.reportUrl + it.id viewModelScope.launch(Dispatchers.IO) { qrCodeBitmap.value = ZQRCodeUtils.generateQRCode(url) }
|