libres icon indicating copy to clipboard operation
libres copied to clipboard

Reading image by name

Open BassirouRabo opened this issue 2 years ago • 5 comments

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

BassirouRabo avatar Oct 24 '23 03:10 BassirouRabo

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.

Skeptick avatar Oct 27 '23 11:10 Skeptick

Could you send sample for android and ios?

BassirouRabo avatar Oct 27 '23 15:10 BassirouRabo

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.

Skeptick avatar Nov 02 '23 18:11 Skeptick

@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 avatar Nov 02 '23 21:11 BassirouRabo

@Skeptick any update regarding this?

BassirouRabo avatar Nov 27 '23 18:11 BassirouRabo