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

dzaitsev

10/21/2023, 10:41 AM
Hey folks! I have a multiplatform project that shares some business code between Android and iOS platforms. I have recently started migrating some views from android to compose multiplatform and have encountered this problem. One of the views used
ImageBitmap
to draw a png image on the canvas, and I can't find a method in mpp to create an object of this type from a resource. Any advice and help would be appreciated.
d

dzaitsev

10/23/2023, 6:49 AM
Yes, of course. There's an example with the java.io API, but I need a multi-platform solution that will work for Android and iOS at the same time. Do I understand correctly that out of the box there is no such solution and I need to use the expect/actual approach?
m

Michael Paus

10/23/2023, 9:56 AM
What exactly is your problem?
Copy code
painter = painterResource("sample.png")
The above code gives you a painter and you can directly draw that into a
DrawScope
without having to use any platform dependent API.
d

dzaitsev

10/23/2023, 10:30 AM
My problem is that
DrawScope
allows to draw `ImageBitmap`s not `Painter`s returned from
painterResource
. I can't just create an instance of
Painter
and draw it on
Canvas
. The canvas API requires
ImageBitmap
. And I can't find a method in mp that can create that
ImageBitmap
from the file path like
imageBitmap("sample.png)
or so.
Solved.
resource("image.png).rememberImageBitmap().orEmpty()
m

Michael Paus

10/23/2023, 12:48 PM
You can draw a painter directly onto a canvas. Here is the code.
Copy code
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource

@Composable
fun TestPainterOnCanvas(modifier: Modifier = Modifier) {
    val painter = painterResource("image.png")
    Canvas(modifier) {
        with(painter) { draw(intrinsicSize) }
    }
}
d

dzaitsev

10/23/2023, 1:06 PM
Thanks @Michael Paus I'll give it a try
2 Views