{% setvar book_path %}/reference/androidx/_book.yaml{% endsetvar %} {% include "_shared/_reference-head-tags.html" %}

PainterResourcesKt

public final class PainterResourcesKt


Summary

Public methods

static final @NonNull Painter

Create a Painter from an Android resource id.

Public methods

painterResource

@Composable
public static final @NonNull Painter painterResource(@DrawableRes int id)

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.

Example:

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp

// 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)
)

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

Example:

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp

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)
                }
            }
        }
)
Parameters
@DrawableRes int id

Resources object to query the image file from

Returns
@NonNull Painter

Painter used for drawing the loaded resource