Show Images from commonMain in KMP Compose Multiplatform

Today’s tutorial teaches us how to show images from commonMain resource folder locally for Android and iOS in KMP compose multiplatform. This concept is known as shared image resources between multiple platforms. So let’s get started.

Show Images from commonMain in KMP Compose Multiplatform

Show Images from commonMain in KMP Compose Multiplatform

Kotlin Compose Multiplatform allows us to use shared resources in a common main folder. We can place images in the resources folder and use those images in both Android & iOS commonly by writing single code.

Steps to put an image in the common resource folder:

1. I am using a sample image in this tutorial. You can download and use this image or use or own it.

Demo Image for KMP tutorial

2. Open Android Studio and paste the image inside

composeApp -> commonMain -> composeResource -> drawable folder.

KMP common resource folder for Image

3. This step is very important. To use the image present in the compose Resource folder we have to rebuild our KMP project. To rebuild the project in Android Studio.

Click on Build -> Rebuild Project.

Rebuild KMP project

4. Now we can call this demo_image.png image in our commonMain shared code in the Image widget.

Code explanation:

  1. painter: Property to assign image which prints on screen from the local shared resource folder.
  2. contentDescription: Description of Image.
  3. modifier: To apply the width and height of the image.
  4. contentScale: To define image scaling.

Complete source code for App.kt file:

Screenshot in Android device:

Local image Android

Screenshot in iOS device:

Show Images from commonMain in KMP Compose Multiplatform

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *