bj0
09/05/2025, 6:16 PMMyClass::class.java.getResource("/images/icon.png")
, but if I try to use it in compose: painterResource("/images/icon.png")
it throws an exception with Resource not found
. I've tried with images/icon.png
and ./images/icon.png
. Does the path need to be different? The files are located in src/main/resources
. I looked at the compose resource library but a lot of the code still uses the java resources as-is so i'm hesitant to convert over, and the project is currently kotlin("jvm")
, not kotlin("multiplatform")
bj0
09/05/2025, 6:17 PMromainguy
09/05/2025, 6:35 PMMichael Paus
09/05/2025, 6:40 PMbj0
09/05/2025, 6:52 PMbj0
09/05/2025, 6:53 PMMichael Paus
09/06/2025, 5:45 AMimplementation(compose.components.resources)
Then put an image into the right folder like this, e.g.:
composeApp/src/commonMain/composeResources/drawable/picture_as_pdf_24px.xml
and then you can call it in your code like this:
Icon(painterResource(Res.drawable.picture_as_pdf_24px), null)
bj0
09/06/2025, 7:15 AMbj0
09/06/2025, 7:16 AMAlexander Maryanovsky
09/06/2025, 9:53 AMfun loadIconBytes(resourcePath: String): ByteArray {
val stream = javaClass.getResourceAsStream(resourcePath) ?:
throw MissingResourceException("Image for icon of $this not found", javaClass.name, resourcePath)
return stream.use { it.readBytes() }
}
private val painterCache = mutableMapOf<String, Painter?>()
@OptIn(ExperimentalResourceApi::class)
@Composable
fun cachedResourcePainter(resourcePath: String): Painter? {
return painterCache.getOrPut(resourcePath) {
runCatching {
val bytes = loadIconBytes(resourcePath)
BitmapPainter(bytes.decodeToImageBitmap())
}.getOrNull()
}
}
@Composable
private fun ResourceImage(
resourcePath: String,,
modifier: Modifier = Modifier,
contentDescription: String?,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
alpha: Float = DefaultAlpha,
colorFilter: ColorFilter? = null
) {
val painter = cachedResourcePainter(resourcePath)
if (painter != null) {
Image(
painter = painter,
contentDescription = contentDescription,
modifier = modifier,
alignment = alignment,
contentScale = contentScale,
alpha = alpha,
colorFilter = colorFilter,
)
} else {
Image(
imageVector = MissingResourceImageVector,
contentDescription = contentDescription,
modifier = modifier,
alignment = alignment,
contentScale = contentScale,
alpha = alpha,
colorFilter = ColorFilter.tint(LocalContentColor.current.copy(alpha = LocalContentAlpha.current))
)
}
}
Alexander Maryanovsky
09/06/2025, 9:57 AMsrc/main/resources
and the latter in src/main/composeResources
.
@Konstantin Tskhovrebov knows for sure.bj0
09/06/2025, 2:30 PMbj0
09/06/2025, 2:49 PM