https://kotlinlang.org logo
#compose
Title
# compose
n

Nick

06/30/2021, 1:13 PM
I want to load this chart into an
AppWidget
on Android. Compose doesn’t work in
AppWidgets
. I believe I saw someone on here mention being able to convert a
Composable
to an
ImageView
? Is that possible?
🚫 1
m

Mark Murphy

06/30/2021, 8:07 PM
In principle, you should be able to get a composable to render to a bitmap-backed
Canvas
. I had a proof-of-concept of that working last year(?), but I have not experimented with it since.
n

Nick

06/30/2021, 8:41 PM
Is your proof of concept open source by any chance?
m

Mark Murphy

06/30/2021, 9:09 PM
Sorry, it looks like I did not keep it around. 😞
😭 1
n

Nick

06/30/2021, 9:52 PM
Do you think I’m getting close?
Copy code
class MainActivity : ComponentActivity() {
    @InternalComposeUiApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.widget)
        val imageView = findViewById<ImageView>(R.id.crypto_icon)

        val composeView = ComposeView(this).apply {
            setContent {
                Column(modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Green)
                ) {
                    Text(
                        text = "lipsum",
                        modifier = Modifier
                            .fillMaxSize()
                            .background(Color.Black),
                        fontSize = 12.sp
                    )
                }
            }
            layoutParams = ViewGroup.LayoutParams(
                300,
                300 
            )

            setParentCompositionContext(imageView.compositionContext)

        }
        val image1 = generateBitmapFromView(composeView)
        findViewById<ImageView>(R.id.crypto_icon).setImageBitmap(image1)
    }
}

fun generateBitmapFromView(view: View): Bitmap {
    val width = 300
    val height =300
    val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    canvas.drawColor(android.graphics.Color.CYAN)
    view.layout(view.left, <http://view.top|view.top>, 300, 300)
    view.draw(canvas)
    return bitmap
}
m

Mark Murphy

06/30/2021, 11:11 PM
Yeah, that's more or less what I was doing. You won't get everything, particularly stuff unique to the GPU (e.g., drop shadows), but it should work for the basics.
❤️ 1