Skeptick / libres

Resources generation in Kotlin Multiplatform
Apache License 2.0
207 stars 11 forks source link

Reading image by name #35

Open BassirouRabo opened 12 months ago

BassirouRabo commented 12 months ago

Is is possible to read image by name as a string at runtime?

Skeptick commented 11 months ago

Hello. Everything is same as in native development. In Android this possible only via reflection. For iOS / JVM / JS you can write helper to get it by string.

BassirouRabo commented 11 months ago

Could you send sample for android and ios?

Skeptick commented 11 months ago

For iOS you need to know name of bundle. You can view it by path yourModule/build/generated/libres/apple/libres-bundles. For example my bundle is named LibresShared

// common
expect fun MainResImages.getByName(name: String, extension: String): Image

// android
actual fun MainResImages.getByName(name: String, extension: String): Image =
   this::class.java.getDeclaredMethod("get${name.replaceFirstChar { it.uppercase() }}").invoke(this) as Image

// ios
actual fun MainResImages.getByName(name: String, extension: String): Image =
    NSBundle.bundleWithName("LibresShared").image(name, extension)

// usage
MainResImages.images.getByName("example", "png")

But you need to remember that in release build of your Android app if you enable obfuscation, names of variables and methods change and such call will cause a runtime crash.

BassirouRabo commented 11 months ago

@Skeptick thanks for you support. It looks like NSBundle.bundleWithName("LibresShared").image(name, extension) returns UIImage instead of Image. I am having issue at this point

BassirouRabo commented 10 months ago

@Skeptick any update regarding this?