androidx.compose.foundation
Canvas
Composable function · from org.jetbrains.compose.foundation:foundation:1.12.2
A Canvas is an empty area you draw on yourself. Use it for charts, gauges, or shapes that no component has.
Canvas(Modifier.size(100.dp)) {
drawCircle(color = Color.Red, radius = size.minDimension / 2)
drawLine(Color.Black, start = Offset.Zero, end = Offset(size.width, size.height), strokeWidth = 4f)
}
Inside the lambda, size is the canvas size in pixels, not dp. Use 4.dp.toPx() to convert. The drawing functions are drawRect, drawCircle, drawLine, drawArc, drawPath, drawImage and more.
A Canvas must have a size: give it one with a modifier. To draw behind or over an existing element instead, use Modifier.drawBehind { } or Modifier.drawWithContent { }; see the Modifier guide.
Basic
For decoration.
@Composable
fun Canvas(modifier: Modifier, onDraw: DrawScope.() -> Unit)
modifier: ModifierRequired
modifier: ModifierRequiredThe size of the canvas, like Modifier.size(100.dp) or Modifier.fillMaxWidth().height(200.dp). Without one, it is empty.
onDraw: DrawScope.() -> UnitRequired
onDraw: DrawScope.() -> UnitRequiredYour drawing code. Runs again when a state it reads changes.
With a description
For drawings that mean something, like a chart.
@Composable
fun Canvas(
modifier: Modifier,
contentDescription: String,
onDraw: DrawScope.() -> Unit,
)
contentDescription: StringRequired
contentDescription: StringRequiredWhat the drawing shows, for screen readers. Like "Sales went up 20 % in May".