Thread
#compose
    Nick

    Nick

    1 year ago
    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?
    m

    Mark Murphy

    1 year ago
    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.
    Nick

    Nick

    1 year ago
    Is your proof of concept open source by any chance?
    m

    Mark Murphy

    1 year ago
    Sorry, it looks like I did not keep it around. 😞
    Nick

    Nick

    1 year ago
    Do you think I’m getting close?
    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

    1 year ago
    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.