painterResource

Composable Function

Android
@Composable
fun painterResource(@DrawableRes id: Int): Painter

Create a Painter from an Android resource id. This can load either an instance of BitmapPainter or VectorPainter for ImageBitmap based assets or vector based assets respectively. The resources with the given id must point to either fully rasterized images (ex. PNG or JPG files) or VectorDrawable xml assets. API based xml Drawables are not supported here.

Alternative Drawable implementations can be used with compose by calling drawIntoCanvas and drawing with the Android framework canvas provided through nativeCanvas

Parameters

idResources object to query the image file from

Returns

Painter used for drawing the loaded resource

Code Examples

PainterResourceSample

@Composable
fun PainterResourceSample() {
    // Sample showing how to render a Painter based on a different resource (vector vs png)
    // Here a Vector asset is used in the portrait orientation, however, a png is used instead
    // in the landscape orientation based on the res/drawable and res/drawable-land-hdpi folders
    Image(
        painterResource(R.drawable.ic_vector_or_png),
        contentDescription = null,
        modifier = Modifier.requiredSize(50.dp),
    )
}

AndroidDrawableInDrawScopeSample

@Composable
fun AndroidDrawableInDrawScopeSample() {
    val drawable = LocalContext.current.getDrawable(R.drawable.sample_drawable)
    Box(
        modifier =
            Modifier.requiredSize(100.dp).drawBehind {
                drawIntoCanvas { canvas ->
                    drawable?.let {
                        it.setBounds(0, 0, size.width.roundToInt(), size.height.roundToInt())
                        it.draw(canvas.nativeCanvas)
                    }
                }
            }
    )
}