androidimagedesktopkotlin-multiplatform

Kotlin Multiplatform ~ Add images on Android and Desktop


I have a problem that I thought would be very simple, but somehow I managed to spend all day searching for a solution and am none the wiser.

Basically, I have a Kotlin Multiplatform app using Compose, which is supposed to work for both Android and Desktop, and so far it does. However, now I want to add a simple title image, and I haven't been able to figure out how to do that.

What I want is to have one image file somewhere - anywhere - in my project structure and have that file be used for both Android and Desktop. Furthermore, I want the image to be loaded in the common UI module, which I think is one of the things that makes this complicated.

As far as I can tell, in Compose, the general way to add an image is like this:

    val image: Painter = painterResource(id = R.drawable.composelogo)
    Image(painter = image,contentDescription = "")

The problem here is that the R seems to be specific to the Android module, while I want to load the image in the common-ui module. For reference, here's my rough project structure:

📁myProject
├📁androidApp
│└📁src
│ └📁main
│  └📁[...]
│   └📄MainActivity.kt <- Uses MainView
├📁desktop
│└📁src
│ └📁jvmMain
│  └📁[...]
│   └📄Main.kt <- Uses MainView
├📁shared
└📁shared-ui
 └📁src
  └📁commonMain
   └📁[...]
    └📄MainView.kt <- Where I want to implement the image display

I've tried out a number of things, including https://github.com/icerockdev/moko-resources , but I couldn't get anything I tried to work. Among the many exciting errors I came across there was one where it suddenly complained that it could not find an AndroidManifest.xml file in the shared-ui folder for whatever reason.

It feels like I am doing something fundamentally wrong here. It shouldn't be that difficult to add a simple image to Android and Desktop at the same time, right?

Can someone please help me out here?

For reference, here's the project where I'm trying to get this working. It also includes a protocol of all the things I already tried: https://github.com/KiraResari/ceal-chronicler


Solution

  • Someone from the moko-resources team helped me implement this now. In order to help anyone who also has this issue, I then wrote the following short how-to guide about what needs to be done to make this work: