To set a dynamically generated drawable as the background, you'll have to convert that drawable into a format that compose can use, such as a Bitmap. Then, you can use an Image composable with a BitmapPainter.
Here is the sample implementation:
Updated
// convert drawable to bitmap
fun drawableToBitmap(drawable: Drawable, width: Int, height: Int): Bitmap {
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, width, height)
drawable.draw(canvas)
return bitmap
}
@Composable
fun LazyColumnWithDynamicBg(
drawable: Drawable,
items: List<String>
) {
var contentHeight by remember {
mutableStateOf(20.dp)
}
var contentWidth by remember {
mutableStateOf(20.dp)
}
Box(modifier = Modifier.wrapContentSize(), contentAlignment = Alignment.TopCenter) {
// get bitmap
val bitmap = drawableToBitmap(drawable, width = contentWidth.value.toInt(), height = contentHeight.value.toInt()) // considering full screen size
Image(
painter = BitmapPainter(bitmap.asImageBitmap()),
contentDescription = null,
modifier = Modifier.matchParentSize()
)
LazyColumn(
modifier = Modifier.fillMaxWidth().wrapContentHeight().onGloballyPositioned {
contentHeight = it.size.height.dp
contentWidth = it.size.width.dp
}
) {
items(items) { item ->
Text(
text = item,
modifier = Modifier.padding(16.dp),
color = Color.White,
fontWeight = FontWeight.Bold
)
}
}
}
}
@Preview
@Composable
fun PreviewComposable() {
// a simple dynamic Drawable for sample
val dynamicDrawable = object : Drawable() {
override fun draw(canvas: Canvas) {
canvas.drawColor(android.graphics.Color.CYAN) // Example: fill the background with cyan color
}
override fun setAlpha(alpha: Int) {}
override fun getOpacity(): Int = android.graphics.PixelFormat.OPAQUE
override fun setColorFilter(colorFilter: android.graphics.ColorFilter?) {}
}
val dummyItems = List(3) { "Item ${it + 1}" }
LazyColumnWithDynamicBg(
drawable = dynamicDrawable,
items = dummyItems
)
}
Output:
