Search code examples
kotlinandroid-jetpack-composeandroid-resourcescoil

How does one display a RawRes in a compose image?


This probably is covered somewhere, but I was unable to find it in the docs / on SO, so I decided to ask:

I've tried this:

@Composable
fun RawImage(
    modifier: Modifier = Modifier,
    @RawRes resource: Int,
    contentDescription: String? = null,
    contentScale: ContentScale = ContentScale.Fit
) {
    AsyncImage(
        modifier = modifier,
        model = LocalContext.current.resources.openRawResource(resource),
        contentDescription = contentDescription,
        contentScale = contentScale
    )
}

and this:

@Composable
fun RawImage(
    modifier: Modifier = Modifier,
    @RawRes resource: Int,
    contentDescription: String? = null,
    contentScale: ContentScale = ContentScale.Fit
) {
    AsyncImage(
        modifier = modifier,
        model = ImageRequest.Builder(LocalContext.current)
            .data(resource)
            .build(),
        contentDescription = contentDescription,
        contentScale = contentScale
    )
}

but so far, both of them don't seem to load the image, so I'm seeking any resources / gists / links that describe how to display a RawRes in Compose, cheers!


Solution

  • If you don't necessarily need to use a raw resource, you can use a drawable-nodpi resource and load it as you would other image resources, which is simpler than trying to use a raw resource. .jpg files are valid drawable resources.