PatilShreyas / Capturable

🚀Jetpack Compose utility library for capturing Composable content and transforming it into Bitmap Image🖼️
https://patilshreyas.github.io/Capturable/
MIT License
980 stars 30 forks source link

[Feature] Support Compose Multiplatform #142

Open egorikftp opened 4 months ago

egorikftp commented 4 months ago

Due to migration to new Modifier API, please consider to add support Compose Multiplatform 🙂

Darkrai9x commented 4 months ago

@PatilShreyas In Compose Multiplatform you can try this for jvm and ios

val pictureRecorder = PictureRecorder()
CacheDrawModifierNode {
            val width = this.size.width
            val height = this.size.height
            onDrawWithContent {
                val pictureCanvas =
                    pictureRecorder.beginRecording(Rect.makeWH(width, height))
                        .asComposeCanvas()
                draw(this, this.layoutDirection, pictureCanvas, this.size) {
                    this@onDrawWithContent.drawContent()
                }
                val picture = pictureRecorder.finishRecordingAsPicture()
                drawIntoCanvas { canvas -> canvas.nativeCanvas.drawPicture(picture) }
            }
        },

And convert picture to ImageBitmap

            val bitmap = org.jetbrains.skia.Bitmap()
            val ci = ColorInfo(
                ColorType.BGRA_8888, ColorAlphaType.OPAQUE, ColorSpace.sRGB,
            )
            bitmap.setImageInfo(ImageInfo(ci, width.toInt(), height.toInt()))
            bitmap.allocN32Pixels(width.toInt(), height.toInt())
            val canvas = org.jetbrains.skia.Canvas(bitmap)
            canvas.drawPicture(picture)
            bitmap.setImmutable()
            bitmap.asComposeImageBitmap()
PatilShreyas commented 4 months ago

Thanks for the insights @Darkrai9x, will try this out. Also, will need to explore this at least for Desktop and iOS platforms and as a low priority for the web as a target.

egorikftp commented 2 months ago

Note: In Compose 1.7+ the API changed https://developer.android.com/develop/ui/compose/graphics/draw/modifiers#composable-to-bitmap

Also looks like new API KMP compatible 🥳