How to create an asset framework for both Android and iOS using Kotlin Multiplatform?


I'm trying to a framework to share webp files for Android and heic files for iOS for the same name of images? For example, I have a file called home . So we will have home.webp for Android and home.heic for iOS. I know we can just put the webp in androidMain/res/drawable-{density}/home.webp for Android. And call it like this:

/// Common Main
expect class PlatformImage 
  
class ImageAsset( 
    val name: String
) { 
    @Composable 
    fun toImage(): PlatformImage? = getPlatformImage() 
  
    override fun toString(): String = name 
} 

@Composable 
internal expect fun ImageAsset.getPlatformImage(): PlatformImage? 

/// Android Main
/// Should manually copy the assets to `androidMain/res/drawable-{density}/` first
actual typealias PlatformImage = Painter 
  
@Composable 
internal actual fun ImageAsset.getPlatformImage(): PlatformImage? { 
    Resources resources = context.getResources();
    final int resourceId = resources.getIdentifier(name, "drawable", 
        context.getPackageName());
    final drawable = resources.getDrawable(resourceId);
    return painterResource(drawable);
} 

But what about iOS? What I had in mind is like this. Is it correct?

/// iOS Main
/// Should manually copy the assets to `iosMain/res/xcassets/` first? Not sure.
/// is this correct?

actual typealias PlatformImage = UIImage 
  
@Composable 
internal actual fun ImageAsset.getPlatformImage(): PlatformImage? { 
    return UIImage.imageNamed(this.name)
} 

Thanks.

PS:

  • The framework will be shared using Gradle for Android and SPM for iOS.
  • The reason we separate the assets like this is because we want to optimize the build for app thinning and the advantage of sizes of both webp and heic.
  • In the iOS main app, the framework will be embedded into it. So the framework's asset catalog should be able to be used on the main app.
0
Apr 20 at 4:09 AM
User AvatarBawenang Rukmoko Pardian Putra
#android#ios#assets#kotlin-multiplatform

No answer found for this question yet.