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

DrawScope

@DrawScopeMarker
public interface DrawScope extends Density

Known direct subclasses
CanvasDrawScope

Implementation of DrawScope that issues drawing commands into the specified canvas and bounds via CanvasDrawScope.draw

ContentDrawScope

Receiver scope for drawing content into a layout, where the content can be drawn between other canvas operations.


Creates a scoped drawing environment with the provided Canvas. This provides a declarative, stateless API to draw shapes and paths without requiring consumers to maintain underlying Canvas state information. DrawScope implementations are also provided sizing information and transformations are done relative to the local translation. That is left and top coordinates are always the origin and the right and bottom coordinates are always the specified width and height respectively. Drawing content is not clipped, so it is possible to draw outside of the specified bounds.

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.inset
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.unit.dp

// Sample showing how to use the DrawScope receiver scope to issue
// drawing commands
Canvas(Modifier.size(120.dp)) {
    drawRect(color = Color.Gray) // Draw grey background
    // Inset content by 10 pixels on the left/right sides and 12 by the
    // top/bottom
    inset(10.0f, 12.0f) {
        val quadrantSize = size / 2.0f

        // Draw a rectangle within the inset bounds
        drawRect(
            size = quadrantSize,
            color = Color.Red
        )

        rotate(45.0f) {
            drawRect(size = quadrantSize, color = Color.Blue)
        }
    }
}

Summary

Nested types

public static class DrawScope.Companion

Public methods

abstract void
drawArc(
    @NonNull Brush brush,
    float startAngle,
    float sweepAngle,
    boolean useCenter,
    @NonNull Offset topLeft,
    @NonNull Size size,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draw an arc scaled to fit inside the given rectangle.

abstract void
drawArc(
    @NonNull Color color,
    float startAngle,
    float sweepAngle,
    boolean useCenter,
    @NonNull Offset topLeft,
    @NonNull Size size,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draw an arc scaled to fit inside the given rectangle.

abstract void
drawCircle(
    @NonNull Brush brush,
    float radius,
    @NonNull Offset center,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a circle at the provided center coordinate and radius.

abstract void
drawCircle(
    @NonNull Color color,
    float radius,
    @NonNull Offset center,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a circle at the provided center coordinate and radius.

abstract void
drawImage(
    @NonNull ImageBitmap image,
    @NonNull Offset topLeft,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws the given ImageBitmap into the canvas with its top-left corner at the given Offset.

default void
drawImage(
    @NonNull ImageBitmap image,
    @NonNull IntOffset srcOffset,
    @NonNull IntSize srcSize,
    @NonNull IntOffset dstOffset,
    @NonNull IntSize dstSize,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode,
    @NonNull FilterQuality filterQuality
)

Draws the subset of the given image described by the src argument into the canvas in the axis-aligned rectangle given by the dst argument.

abstract void
drawLine(
    @NonNull Brush brush,
    @NonNull Offset start,
    @NonNull Offset end,
    float strokeWidth,
    @NonNull StrokeCap cap,
    PathEffect pathEffect,
    float alpha,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a line between the given points using the given paint.

abstract void
drawLine(
    @NonNull Color color,
    @NonNull Offset start,
    @NonNull Offset end,
    float strokeWidth,
    @NonNull StrokeCap cap,
    PathEffect pathEffect,
    float alpha,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a line between the given points using the given paint.

abstract void
drawOval(
    @NonNull Brush brush,
    @NonNull Offset topLeft,
    @NonNull Size size,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws an oval with the given offset and size.

abstract void
drawOval(
    @NonNull Color color,
    @NonNull Offset topLeft,
    @NonNull Size size,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws an oval with the given offset and size.

abstract void
drawPath(
    @NonNull Path path,
    @NonNull Brush brush,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws the given Path with the given Color.

abstract void
drawPath(
    @NonNull Path path,
    @NonNull Color color,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws the given Path with the given Color.

abstract void
drawPoints(
    @NonNull List<@NonNull Offset> points,
    @NonNull PointMode pointMode,
    @NonNull Brush brush,
    float strokeWidth,
    @NonNull StrokeCap cap,
    PathEffect pathEffect,
    float alpha,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a sequence of points according to the given PointMode.

abstract void
drawPoints(
    @NonNull List<@NonNull Offset> points,
    @NonNull PointMode pointMode,
    @NonNull Color color,
    float strokeWidth,
    @NonNull StrokeCap cap,
    PathEffect pathEffect,
    float alpha,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a sequence of points according to the given PointMode.

abstract void
drawRect(
    @NonNull Brush brush,
    @NonNull Offset topLeft,
    @NonNull Size size,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a rectangle with the given offset and size.

abstract void
drawRect(
    @NonNull Color color,
    @NonNull Offset topLeft,
    @NonNull Size size,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a rectangle with the given offset and size.

abstract void
drawRoundRect(
    @NonNull Brush brush,
    @NonNull Offset topLeft,
    @NonNull Size size,
    @NonNull CornerRadius cornerRadius,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a rounded rectangle with the provided size, offset and radii for the x and y axis respectively.

abstract void
drawRoundRect(
    @NonNull Color color,
    @NonNull Offset topLeft,
    @NonNull Size size,
    @NonNull CornerRadius cornerRadius,
    @NonNull DrawStyle style,
    float alpha,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a rounded rectangle with the given Paint.

default @NonNull Offset

Center of the current bounds of the drawing environment

abstract @NonNull DrawContext

The current DrawContext that contains the dependencies needed to create the drawing environment

abstract @NonNull LayoutDirection

The layout direction of the layout being drawn in.

default @NonNull Size

Provides the dimensions of the current drawing environment

Extension functions

default final void
DrawScopeKt.clipPath(
    @NonNull DrawScope receiver,
    @NonNull Path path,
    @NonNull ClipOp clipOp,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Reduces the clip region to the intersection of the current clip and the given path.

default final void
DrawScopeKt.clipRect(
    @NonNull DrawScope receiver,
    float left,
    float top,
    float right,
    float bottom,
    @NonNull ClipOp clipOp,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Reduces the clip region to the intersection of the current clip and the given rectangle indicated by the given left, top, right and bottom bounds.

default final void
DrawScopeKt.drawIntoCanvas(
    @NonNull DrawScope receiver,
    @NonNull Function1<@NonNull CanvasUnit> block
)

Provides access to draw directly with the underlying Canvas.

default final void
DrawScopeKt.inset(
    @NonNull DrawScope receiver,
    float inset,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Convenience method modifies the DrawScope bounds to inset both left, top, right and bottom bounds by inset.

default final void
DrawScopeKt.inset(
    @NonNull DrawScope receiver,
    float horizontal,
    float vertical,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Convenience method modifies the DrawScope bounds to inset both left and right bounds by horizontal as well as the top and bottom by vertical.

default final void
DrawScopeKt.inset(
    @NonNull DrawScope receiver,
    float left,
    float top,
    float right,
    float bottom,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Simultaneously translate the DrawScope coordinate space by left and top as well as modify the dimensions of the current painting area.

default final void
DrawScopeKt.rotate(
    @NonNull DrawScope receiver,
    float degrees,
    @NonNull Offset pivot,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Add a rotation (in degrees clockwise) to the current transform at the given pivot point.

default final void
DrawScopeKt.rotateRad(
    @NonNull DrawScope receiver,
    float radians,
    @NonNull Offset pivot,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Add a rotation (in radians clockwise) to the current transform at the given pivot point.

default final void
DrawScopeKt.scale(
    @NonNull DrawScope receiver,
    float scale,
    @NonNull Offset pivot,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Add an axis-aligned scale to the current transform, scaling both the horizontal direction and the vertical direction at the given pivot coordinate.

default final void
DrawScopeKt.scale(
    @NonNull DrawScope receiver,
    float scaleX,
    float scaleY,
    @NonNull Offset pivot,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Add an axis-aligned scale to the current transform, scaling by the first argument in the horizontal direction and the second in the vertical direction at the given pivot coordinate.

default final void
DrawScopeKt.translate(
    @NonNull DrawScope receiver,
    float left,
    float top,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Translate the coordinate space by the given delta in pixels in both the x and y coordinates respectively

default final void
DrawScopeKt.withTransform(
    @NonNull DrawScope receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawTransformUnit> transformBlock,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> drawBlock
)

Perform 1 or more transformations and execute drawing commands with the specified transformations applied.

default final void
OutlineKt.drawOutline(
    @NonNull DrawScope receiver,
    @NonNull Outline outline,
    @NonNull Brush brush,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws the Outline on a DrawScope.

default final void
OutlineKt.drawOutline(
    @NonNull DrawScope receiver,
    @NonNull Outline outline,
    @NonNull Color color,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws the Outline on a DrawScope.

default final void
TextPainterKt.drawText(
    @NonNull DrawScope receiver,
    @NonNull TextLayoutResult textLayoutResult,
    @NonNull Brush brush,
    @NonNull Offset topLeft,
    float alpha,
    Shadow shadow,
    TextDecoration textDecoration,
    DrawStyle drawStyle,
    @NonNull BlendMode blendMode
)

Draw an existing text layout as produced by TextMeasurer.

default final void
TextPainterKt.drawText(
    @NonNull DrawScope receiver,
    @NonNull TextLayoutResult textLayoutResult,
    @NonNull Color color,
    @NonNull Offset topLeft,
    float alpha,
    Shadow shadow,
    TextDecoration textDecoration,
    DrawStyle drawStyle,
    @NonNull BlendMode blendMode
)

Draw an existing text layout as produced by TextMeasurer.

default final void
TextPainterKt.drawText(
    @NonNull DrawScope receiver,
    @NonNull TextMeasurer textMeasurer,
    @NonNull String text,
    @NonNull Offset topLeft,
    @NonNull TextStyle style,
    @NonNull TextOverflow overflow,
    boolean softWrap,
    int maxLines,
    @NonNull Size size,
    @NonNull BlendMode blendMode
)

Draw text using a TextMeasurer.

default final void
TextPainterKt.drawText(
    @NonNull DrawScope receiver,
    @NonNull TextMeasurer textMeasurer,
    @NonNull AnnotatedString text,
    @NonNull Offset topLeft,
    @NonNull TextStyle style,
    @NonNull TextOverflow overflow,
    boolean softWrap,
    int maxLines,
    @NonNull List<@NonNull AnnotatedString.Range<@NonNull Placeholder>> placeholders,
    @NonNull Size size,
    @NonNull BlendMode blendMode
)

Draw styled text using a TextMeasurer.

Inherited methods

From androidx.compose.ui.unit.Density
abstract float

The logical density of the display.

abstract float

Current user preference for the scaling factor for fonts.

default int

Convert Dp to Int by rounding

default int

Convert Sp to Int by rounding

default @NonNull Dp

Convert Sp to Dp.

default @NonNull Dp
orgKt.toDp(int receiver)

Convert an Int pixel value to Dp.

default @NonNull Dp
orgKt.toDp(float receiver)

Convert a Float pixel value to a Dp

default @NonNull DpSize

Convert a Size to a DpSize.

default float
orgKt.toPx(@NonNull Dp receiver)

Convert Dp to pixels.

default float

Convert Sp to pixels.

default @NonNull Rect

Convert a DpRect to a Rect.

default @NonNull Size

Convert a DpSize to a Size.

default @NonNull TextUnit
orgKt.toSp(@NonNull Dp receiver)

Convert Dp to Sp.

default @NonNull TextUnit
orgKt.toSp(int receiver)

Convert an Int pixel value to Sp.

default @NonNull TextUnit
orgKt.toSp(float receiver)

Convert a Float pixel value to a Sp

Public methods

drawArc

abstract void drawArc(
    @NonNull Brush brush,
    float startAngle,
    float sweepAngle,
    boolean useCenter,
    @NonNull Offset topLeft,
    @NonNull Size size,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draw an arc scaled to fit inside the given rectangle. It starts from startAngle degrees around the oval up to startAngle + sweepAngle degrees around the oval, with zero degrees being the point on the right hand side of the oval that crosses the horizontal line that intersects the center of the rectangle and with positive angles going clockwise around the oval. If useCenter is true, the arc is closed back to the center, forming a circle sector. Otherwise, the arc is not closed, forming a circle segment.

Parameters
@NonNull Brush brush

Color or fill to be applied to the arc

float startAngle

Starting angle in degrees. 0 represents 3 o'clock

float sweepAngle

Size of the arc in degrees that is drawn clockwise relative to startAngle

boolean useCenter

Flag indicating if the arc is to close the center of the bounds

@NonNull Offset topLeft

Offset from the local origin of 0, 0 relative to the current translation

@NonNull Size size

Dimensions of the arc to draw

float alpha

Opacity to be applied to the arc from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Whether or not the arc is stroked or filled in

ColorFilter colorFilter

ColorFilter to apply to the brush when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to be applied to the arc when it is drawn

drawArc

abstract void drawArc(
    @NonNull Color color,
    float startAngle,
    float sweepAngle,
    boolean useCenter,
    @NonNull Offset topLeft,
    @NonNull Size size,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draw an arc scaled to fit inside the given rectangle. It starts from startAngle degrees around the oval up to startAngle + sweepAngle degrees around the oval, with zero degrees being the point on the right hand side of the oval that crosses the horizontal line that intersects the center of the rectangle and with positive angles going clockwise around the oval. If useCenter is true, the arc is closed back to the center, forming a circle sector. Otherwise, the arc is not closed, forming a circle segment.

Parameters
@NonNull Color color

Color to be applied to the arc

float startAngle

Starting angle in degrees. 0 represents 3 o'clock

float sweepAngle

Size of the arc in degrees that is drawn clockwise relative to startAngle

boolean useCenter

Flag indicating if the arc is to close the center of the bounds

@NonNull Offset topLeft

Offset from the local origin of 0, 0 relative to the current translation

@NonNull Size size

Dimensions of the arc to draw

float alpha

Opacity to be applied to the arc from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Whether or not the arc is stroked or filled in

ColorFilter colorFilter

ColorFilter to apply to the color when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to be applied to the arc when it is drawn

drawCircle

abstract void drawCircle(
    @NonNull Brush brush,
    float radius,
    @NonNull Offset center,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a circle at the provided center coordinate and radius. If no center point is provided the center of the bounds is used.

Parameters
@NonNull Brush brush

The color or fill to be applied to the circle

float radius

The radius of the circle

@NonNull Offset center

The center coordinate where the circle is to be drawn

float alpha

Opacity to be applied to the circle from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Whether or not the circle is stroked or filled in

ColorFilter colorFilter

ColorFilter to apply to the brush when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to be applied to the brush

drawCircle

abstract void drawCircle(
    @NonNull Color color,
    float radius,
    @NonNull Offset center,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a circle at the provided center coordinate and radius. If no center point is provided the center of the bounds is used.

Parameters
@NonNull Color color

The color or fill to be applied to the circle

float radius

The radius of the circle

@NonNull Offset center

The center coordinate where the circle is to be drawn

float alpha

Opacity to be applied to the circle from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Whether or not the circle is stroked or filled in

ColorFilter colorFilter

ColorFilter to apply to the color when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to be applied to the brush

drawImage

abstract void drawImage(
    @NonNull ImageBitmap image,
    @NonNull Offset topLeft,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws the given ImageBitmap into the canvas with its top-left corner at the given Offset. The image is composited into the canvas using the given Paint.

Parameters
@NonNull ImageBitmap image

The ImageBitmap to draw

@NonNull Offset topLeft

Offset from the local origin of 0, 0 relative to the current translation

float alpha

Opacity to be applied to image from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Specifies whether the image is to be drawn filled in or as a rectangular stroke

ColorFilter colorFilter

ColorFilter to apply to the image when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to apply to destination

drawImage

default void drawImage(
    @NonNull ImageBitmap image,
    @NonNull IntOffset srcOffset,
    @NonNull IntSize srcSize,
    @NonNull IntOffset dstOffset,
    @NonNull IntSize dstSize,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode,
    @NonNull FilterQuality filterQuality
)

Draws the subset of the given image described by the src argument into the canvas in the axis-aligned rectangle given by the dst argument.

If no src rect is provided, the entire image is scaled into the corresponding destination bounds

Parameters
@NonNull ImageBitmap image

The source image to draw

@NonNull IntOffset srcOffset

Optional offset representing the top left offset of the source image to draw, this defaults to the origin of image

@NonNull IntSize srcSize

Optional dimensions of the source image to draw relative to srcOffset, this defaults the width and height of image

@NonNull IntOffset dstOffset

Optional offset representing the top left offset of the destination to draw the given image, this defaults to the origin of the current translation tarting top left offset in the destination to draw the image

@NonNull IntSize dstSize

Optional dimensions of the destination to draw, this defaults to srcSize

float alpha

Opacity to be applied to image from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Specifies whether the image is to be drawn filled in or as a rectangular stroke

ColorFilter colorFilter

ColorFilter to apply to the image when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to apply to destination

@NonNull FilterQuality filterQuality

Sampling algorithm applied to the image when it is scaled and drawn into the destination. The default is FilterQuality.Low which scales using a bilinear sampling algorithm

drawLine

abstract void drawLine(
    @NonNull Brush brush,
    @NonNull Offset start,
    @NonNull Offset end,
    float strokeWidth,
    @NonNull StrokeCap cap,
    PathEffect pathEffect,
    float alpha,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a line between the given points using the given paint. The line is stroked.

Parameters
@NonNull Brush brush

the color or fill to be applied to the line

@NonNull Offset start

first point of the line to be drawn

@NonNull Offset end

second point of the line to be drawn

float strokeWidth

stroke width to apply to the line

@NonNull StrokeCap cap

treatment applied to the ends of the line segment

PathEffect pathEffect

optional effect or pattern to apply to the line

float alpha

opacity to be applied to the brush from 0.0f to 1.0f representing fully transparent to fully opaque respectively

ColorFilter colorFilter

ColorFilter to apply to the brush when drawn into the destination

@NonNull BlendMode blendMode

the blending algorithm to apply to the brush

drawLine

abstract void drawLine(
    @NonNull Color color,
    @NonNull Offset start,
    @NonNull Offset end,
    float strokeWidth,
    @NonNull StrokeCap cap,
    PathEffect pathEffect,
    float alpha,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a line between the given points using the given paint. The line is stroked.

Parameters
@NonNull Color color

the color to be applied to the line

@NonNull Offset start

first point of the line to be drawn

@NonNull Offset end

second point of the line to be drawn

float strokeWidth

The stroke width to apply to the line

@NonNull StrokeCap cap

treatment applied to the ends of the line segment

PathEffect pathEffect

optional effect or pattern to apply to the line

float alpha

opacity to be applied to the color from 0.0f to 1.0f representing fully transparent to fully opaque respectively

ColorFilter colorFilter

ColorFilter to apply to the color when drawn into the destination

@NonNull BlendMode blendMode

the blending algorithm to apply to the color

drawOval

abstract void drawOval(
    @NonNull Brush brush,
    @NonNull Offset topLeft,
    @NonNull Size size,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws an oval with the given offset and size. If no offset from the top left is provided, it is drawn starting from the origin of the current translation. If no size is provided, the size of the current environment is used.

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Canvas(Modifier.size(120.dp)) {
    drawOval(
        brush = Brush.linearGradient(listOf(Color.Red, Color.Blue)),
        topLeft = Offset(10f, 10f),
        size = Size(size.width - 20f, size.height - 20f)
    )
}
Parameters
@NonNull Brush brush

Color or fill to be applied to the oval

@NonNull Offset topLeft

Offset from the local origin of 0, 0 relative to the current translation

@NonNull Size size

Dimensions of the rectangle to draw

float alpha

Opacity to be applied to the oval from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Whether or not the oval is stroked or filled in

ColorFilter colorFilter

ColorFilter to apply to the brush when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to be applied to the brush

drawOval

abstract void drawOval(
    @NonNull Color color,
    @NonNull Offset topLeft,
    @NonNull Size size,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws an oval with the given offset and size. If no offset from the top left is provided, it is drawn starting from the origin of the current translation. If no size is provided, the size of the current environment is used.

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

Canvas(Modifier.size(120.dp)) {
    drawOval(
        color = Color.Cyan,
        topLeft = Offset(10f, 10f),
        size = Size(size.width - 20f, size.height - 20f)
    )
}
Parameters
@NonNull Color color

Color to be applied to the oval

@NonNull Offset topLeft

Offset from the local origin of 0, 0 relative to the current translation

@NonNull Size size

Dimensions of the rectangle to draw

float alpha

Opacity to be applied to the oval from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Whether or not the oval is stroked or filled in

ColorFilter colorFilter

ColorFilter to apply to the color when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to be applied to the brush

drawPath

abstract void drawPath(
    @NonNull Path path,
    @NonNull Brush brush,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws the given Path with the given Color. Whether this shape is filled or stroked (or both) is controlled by DrawStyle. If the path is filled, then subpaths within it are implicitly closed (see Path.close).

Parameters
@NonNull Path path

Path to draw

@NonNull Brush brush

Brush to be applied to the path

float alpha

Opacity to be applied to the path from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Whether or not the path is stroked or filled in

ColorFilter colorFilter

ColorFilter to apply to the brush when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to be applied to the path when it is drawn

drawPath

abstract void drawPath(
    @NonNull Path path,
    @NonNull Color color,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws the given Path with the given Color. Whether this shape is filled or stroked (or both) is controlled by DrawStyle. If the path is filled, then subpaths within it are implicitly closed (see Path.close).

Parameters
@NonNull Path path

Path to draw

@NonNull Color color

Color to be applied to the path

float alpha

Opacity to be applied to the path from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Whether or not the path is stroked or filled in

ColorFilter colorFilter

ColorFilter to apply to the color when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to be applied to the path when it is drawn

drawPoints

abstract void drawPoints(
    @NonNull List<@NonNull Offset> points,
    @NonNull PointMode pointMode,
    @NonNull Brush brush,
    float strokeWidth,
    @NonNull StrokeCap cap,
    PathEffect pathEffect,
    float alpha,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a sequence of points according to the given PointMode.

The points argument is interpreted as offsets from the origin.

Parameters
@NonNull List<@NonNull Offset> points

List of points to draw with the specified PointMode

@NonNull PointMode pointMode

PointMode used to indicate how the points are to be drawn

@NonNull Brush brush

Brush to be applied to the points

float strokeWidth

The stroke width to apply to the line

@NonNull StrokeCap cap

Treatment applied to the ends of the line segment

PathEffect pathEffect

optional effect or pattern to apply to the points

float alpha

Opacity to be applied to the path from 0.0f to 1.0f representing fully transparent to fully opaque respectively.

ColorFilter colorFilter

ColorFilter to apply to the brush when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to be applied to the path when it is drawn

drawPoints

abstract void drawPoints(
    @NonNull List<@NonNull Offset> points,
    @NonNull PointMode pointMode,
    @NonNull Color color,
    float strokeWidth,
    @NonNull StrokeCap cap,
    PathEffect pathEffect,
    float alpha,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a sequence of points according to the given PointMode.

The points argument is interpreted as offsets from the origin.

Parameters
@NonNull List<@NonNull Offset> points

List of points to draw with the specified PointMode

@NonNull PointMode pointMode

PointMode used to indicate how the points are to be drawn

@NonNull Color color

Color to be applied to the points

float strokeWidth

The stroke width to apply to the line

@NonNull StrokeCap cap

Treatment applied to the ends of the line segment

PathEffect pathEffect

optional effect or pattern to apply to the point

float alpha

Opacity to be applied to the path from 0.0f to 1.0f representing fully transparent to fully opaque respectively

ColorFilter colorFilter

ColorFilter to apply to the color when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to be applied to the path when it is drawn

drawRect

abstract void drawRect(
    @NonNull Brush brush,
    @NonNull Offset topLeft,
    @NonNull Size size,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a rectangle with the given offset and size. If no offset from the top left is provided, it is drawn starting from the origin of the current translation. If no size is provided, the size of the current environment is used.

Parameters
@NonNull Brush brush

The color or fill to be applied to the rectangle

@NonNull Offset topLeft

Offset from the local origin of 0, 0 relative to the current translation

@NonNull Size size

Dimensions of the rectangle to draw

float alpha

Opacity to be applied to the brush from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Whether or not the rectangle is stroked or filled in

ColorFilter colorFilter

ColorFilter to apply to the brush when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to apply to destination

drawRect

abstract void drawRect(
    @NonNull Color color,
    @NonNull Offset topLeft,
    @NonNull Size size,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a rectangle with the given offset and size. If no offset from the top left is provided, it is drawn starting from the origin of the current translation. If no size is provided, the size of the current environment is used.

Parameters
@NonNull Color color

The color to be applied to the rectangle

@NonNull Offset topLeft

Offset from the local origin of 0, 0 relative to the current translation

@NonNull Size size

Dimensions of the rectangle to draw

float alpha

Opacity to be applied to the color from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Whether or not the rectangle is stroked or filled in

ColorFilter colorFilter

ColorFilter to apply to the color source pixels

@NonNull BlendMode blendMode

Blending algorithm to apply to destination

drawRoundRect

abstract void drawRoundRect(
    @NonNull Brush brush,
    @NonNull Offset topLeft,
    @NonNull Size size,
    @NonNull CornerRadius cornerRadius,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a rounded rectangle with the provided size, offset and radii for the x and y axis respectively. This rectangle is drawn with the provided Brush parameter and is filled or stroked based on the given DrawStyle

Parameters
@NonNull Brush brush

The color or fill to be applied to the rounded rectangle

@NonNull Offset topLeft

Offset from the local origin of 0, 0 relative to the current translation

@NonNull Size size

Dimensions of the rectangle to draw

@NonNull CornerRadius cornerRadius

Corner radius of the rounded rectangle, negative radii values are clamped to 0

float alpha

Opacity to be applied to rounded rectangle from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Specifies whether the rounded rectangle is stroked or filled in

ColorFilter colorFilter

ColorFilter to apply to the brush when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to be applied to the brush

drawRoundRect

abstract void drawRoundRect(
    @NonNull Color color,
    @NonNull Offset topLeft,
    @NonNull Size size,
    @NonNull CornerRadius cornerRadius,
    @NonNull DrawStyle style,
    float alpha,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws a rounded rectangle with the given Paint. Whether the rectangle is filled or stroked (or both) is controlled by Paint.style.

Parameters
@NonNull Color color

The color to be applied to the rounded rectangle

@NonNull Offset topLeft

Offset from the local origin of 0, 0 relative to the current translation

@NonNull Size size

Dimensions of the rectangle to draw

@NonNull CornerRadius cornerRadius

Corner radius of the rounded rectangle, negative radii values are clamped to 0

@NonNull DrawStyle style

Specifies whether the rounded rectangle is stroked or filled in

float alpha

Opacity to be applied to rounded rectangle from 0.0f to 1.0f representing fully transparent to fully opaque respectively

ColorFilter colorFilter

ColorFilter to apply to the color when drawn into the destination

@NonNull BlendMode blendMode

Blending algorithm to be applied to the color

getCenter

default @NonNull Offset getCenter()

Center of the current bounds of the drawing environment

getDrawContext

abstract @NonNull DrawContext getDrawContext()

The current DrawContext that contains the dependencies needed to create the drawing environment

getLayoutDirection

abstract @NonNull LayoutDirection getLayoutDirection()

The layout direction of the layout being drawn in.

getSize

default @NonNull Size getSize()

Provides the dimensions of the current drawing environment

Extension functions

DrawScopeKt.clipPath

default final void DrawScopeKt.clipPath(
    @NonNull DrawScope receiver,
    @NonNull Path path,
    @NonNull ClipOp clipOp,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Reduces the clip region to the intersection of the current clip and the given path. This method provides a callback to issue drawing commands within the region defined by the clipped path. After this method is invoked, this clip is no longer applied.

Parameters
@NonNull Path path

Shape to clip drawing content within

@NonNull ClipOp clipOp

Clipping operation to conduct on the given bounds, defaults to ClipOp.Intersect

@ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block

Lambda callback with this CanvasScope as a receiver scope to issue drawing commands within the provided clip

DrawScopeKt.clipRect

default final void DrawScopeKt.clipRect(
    @NonNull DrawScope receiver,
    float left,
    float top,
    float right,
    float bottom,
    @NonNull ClipOp clipOp,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Reduces the clip region to the intersection of the current clip and the given rectangle indicated by the given left, top, right and bottom bounds. This provides a callback to issue drawing commands within the clipped region. After this method is invoked, this clip is no longer applied.

Use ClipOp.Difference to subtract the provided rectangle from the current clip.

Parameters
float left

Left bound of the rectangle to clip

float top

Top bound of the rectangle to clip

float right

Right bound of the rectangle to clip

float bottom

Bottom bound of the rectangle to clip

@NonNull ClipOp clipOp

Clipping operation to conduct on the given bounds, defaults to ClipOp.Intersect

@ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block

Lambda callback with this CanvasScope as a receiver scope to issue drawing commands within the provided clip

DrawScopeKt.drawIntoCanvas

default final void DrawScopeKt.drawIntoCanvas(
    @NonNull DrawScope receiver,
    @NonNull Function1<@NonNull CanvasUnit> block
)

Provides access to draw directly with the underlying Canvas. This is helpful for situations to re-use alternative drawing logic in combination with DrawScope

Parameters
@NonNull Function1<@NonNull CanvasUnit> block

Lambda callback to issue drawing commands on the provided Canvas

DrawScopeKt.inset

default final void DrawScopeKt.inset(
    @NonNull DrawScope receiver,
    float inset,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Convenience method modifies the DrawScope bounds to inset both left, top, right and bottom bounds by inset. After this method is invoked, the coordinate space is returned to the state before this inset was applied.

Parameters
float inset

number of pixels to inset left, top, right, and bottom bounds.

@ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block

lambda that is called to issue additional drawing commands within the modified coordinate space

DrawScopeKt.inset

default final void DrawScopeKt.inset(
    @NonNull DrawScope receiver,
    float horizontal,
    float vertical,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Convenience method modifies the DrawScope bounds to inset both left and right bounds by horizontal as well as the top and bottom by vertical. After this method is invoked, the coordinate space is returned to the state before this inset was applied.

Parameters
float horizontal

number of pixels to inset both left and right bounds. Zero by default

float vertical

Optional number of pixels to inset both top and bottom bounds. Zero by default

@ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block

lambda that is called to issue additional drawing commands within the modified coordinate space

DrawScopeKt.inset

default final void DrawScopeKt.inset(
    @NonNull DrawScope receiver,
    float left,
    float top,
    float right,
    float bottom,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Simultaneously translate the DrawScope coordinate space by left and top as well as modify the dimensions of the current painting area. This provides a callback to issue more drawing instructions within the modified coordinate space. This method modifies the width of the DrawScope to be equivalent to width - (left + right) as well as height to height - (top + bottom). After this method is invoked, the coordinate space is returned to the state before the inset was applied.

Parameters
float left

number of pixels to inset the left drawing bound

float top

number of pixels to inset the top drawing bound

float right

number of pixels to inset the right drawing bound

float bottom

number of pixels to inset the bottom drawing bound

@ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block

lambda that is called to issue drawing commands within the inset coordinate space

DrawScopeKt.rotate

default final void DrawScopeKt.rotate(
    @NonNull DrawScope receiver,
    float degrees,
    @NonNull Offset pivot,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Add a rotation (in degrees clockwise) to the current transform at the given pivot point. The pivot coordinate remains unchanged by the rotation transformation. After the provided lambda is invoked, the rotation transformation is undone.

Parameters
float degrees

to rotate clockwise

@NonNull Offset pivot

The coordinate for the pivot point, defaults to the center of the coordinate space

@ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block

lambda that is called to issue drawing commands within the rotated coordinate space

DrawScopeKt.rotateRad

default final void DrawScopeKt.rotateRad(
    @NonNull DrawScope receiver,
    float radians,
    @NonNull Offset pivot,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Add a rotation (in radians clockwise) to the current transform at the given pivot point. The pivot coordinate remains unchanged by the rotation transformation

Parameters
float radians

to rotate clockwise

@NonNull Offset pivot

The coordinate for the pivot point, defaults to the center of the coordinate space

@ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block

lambda that is called to issue drawing commands within the rotated coordinate space

DrawScopeKt.scale

default final void DrawScopeKt.scale(
    @NonNull DrawScope receiver,
    float scale,
    @NonNull Offset pivot,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Add an axis-aligned scale to the current transform, scaling both the horizontal direction and the vertical direction at the given pivot coordinate. The pivot coordinate remains unchanged by the scale transformation. After this method is invoked, the coordinate space is returned to the state before the scale was applied.

Parameters
float scale

The amount to scale uniformly in both directions

@NonNull Offset pivot

The coordinate for the pivot point, defaults to the center of the coordinate space

@ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block

lambda used to issue drawing commands within the scaled coordinate space

DrawScopeKt.scale

default final void DrawScopeKt.scale(
    @NonNull DrawScope receiver,
    float scaleX,
    float scaleY,
    @NonNull Offset pivot,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Add an axis-aligned scale to the current transform, scaling by the first argument in the horizontal direction and the second in the vertical direction at the given pivot coordinate. The pivot coordinate remains unchanged by the scale transformation. After this method is invoked, the coordinate space is returned to the state before the scale was applied.

Parameters
float scaleX

The amount to scale in X

float scaleY

The amount to scale in Y

@NonNull Offset pivot

The coordinate for the pivot point, defaults to the center of the coordinate space

@ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block

lambda used to issue drawing commands within the scaled coordinate space

DrawScopeKt.translate

default final void DrawScopeKt.translate(
    @NonNull DrawScope receiver,
    float left,
    float top,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block
)

Translate the coordinate space by the given delta in pixels in both the x and y coordinates respectively

Parameters
float left

Pixels to translate the coordinate space in the x-axis

float top

Pixels to translate the coordinate space in the y-axis

@ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> block

lambda that is called to issue drawing commands within the translated coordinate space

DrawScopeKt.withTransform

default final void DrawScopeKt.withTransform(
    @NonNull DrawScope receiver,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawTransformUnit> transformBlock,
    @ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> drawBlock
)

Perform 1 or more transformations and execute drawing commands with the specified transformations applied. After this call is complete, the transformation before this call was made is restored

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.inset
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.unit.dp

Canvas(Modifier.size(120.dp)) { // CanvasScope
    inset(20.0f) {
        // Use withTransform to batch multiple transformations for 1 or more drawing calls
        // that are to be drawn.
        // This is more efficient than issuing nested translation, rotation and scaling
        // calls as the internal state is saved once before and after instead of multiple
        // times between each transformation if done individually
        withTransform({
            translate(10.0f, 12.0f)
            rotate(45.0f, center)
            scale(2.0f, 0.5f)
        }) {
            drawRect(Color.Cyan)
            drawCircle(Color.Blue)
        }
        drawRect(Color.Red, alpha = 0.25f)
    }
}
Parameters
@ExtensionFunctionType @NonNull Function1<@NonNull DrawTransformUnit> transformBlock

Callback invoked to issue transformations to be made before the drawing operations are issued

@ExtensionFunctionType @NonNull Function1<@NonNull DrawScopeUnit> drawBlock

Callback invoked to issue drawing operations after the transformations are applied

OutlineKt.drawOutline

default final void OutlineKt.drawOutline(
    @NonNull DrawScope receiver,
    @NonNull Outline outline,
    @NonNull Brush brush,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws the Outline on a DrawScope.

Parameters
@NonNull Outline outline

the outline to draw.

@NonNull Brush brush

Brush applied to the outline when it is drawn

float alpha

Opacity to be applied to outline from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Specifies whether the outline is stroked or filled in

ColorFilter colorFilter

: ColorFilter to apply to the Brush when drawn into the destination

@NonNull BlendMode blendMode

: Blending algorithm to be applied to the outline

OutlineKt.drawOutline

default final void OutlineKt.drawOutline(
    @NonNull DrawScope receiver,
    @NonNull Outline outline,
    @NonNull Color color,
    float alpha,
    @NonNull DrawStyle style,
    ColorFilter colorFilter,
    @NonNull BlendMode blendMode
)

Draws the Outline on a DrawScope.

Parameters
@NonNull Outline outline

the outline to draw.

@NonNull Color color

Color applied to the outline when it is drawn

float alpha

Opacity to be applied to outline from 0.0f to 1.0f representing fully transparent to fully opaque respectively

@NonNull DrawStyle style

Specifies whether the outline is stroked or filled in

ColorFilter colorFilter

: ColorFilter to apply to the color when drawn into the destination

@NonNull BlendMode blendMode

: Blending algorithm to be applied to the outline

TextPainterKt.drawText

default final void TextPainterKt.drawText(
    @NonNull DrawScope receiver,
    @NonNull TextLayoutResult textLayoutResult,
    @NonNull Brush brush,
    @NonNull Offset topLeft,
    float alpha,
    Shadow shadow,
    TextDecoration textDecoration,
    DrawStyle drawStyle,
    @NonNull BlendMode blendMode
)

Draw an existing text layout as produced by TextMeasurer.

This draw function cannot relayout when async font loading resolves. If using async fonts or other dynamic text layout, you are responsible for invalidating layout on changes.

Parameters
@NonNull TextLayoutResult textLayoutResult

Text Layout to be drawn

@NonNull Brush brush

The brush to use when drawing the text.

@NonNull Offset topLeft

Offsets the text from top left point of the current coordinate system.

float alpha

Opacity to be applied to brush from 0.0f to 1.0f representing fully transparent to fully opaque respectively.

Shadow shadow

The shadow effect applied on the text.

TextDecoration textDecoration

The decorations to paint on the text (e.g., an underline).

DrawStyle drawStyle

Whether or not the text is stroked or filled in.

@NonNull BlendMode blendMode

Blending algorithm to be applied to the text

TextPainterKt.drawText

default final void TextPainterKt.drawText(
    @NonNull DrawScope receiver,
    @NonNull TextLayoutResult textLayoutResult,
    @NonNull Color color,
    @NonNull Offset topLeft,
    float alpha,
    Shadow shadow,
    TextDecoration textDecoration,
    DrawStyle drawStyle,
    @NonNull BlendMode blendMode
)

Draw an existing text layout as produced by TextMeasurer.

This draw function cannot relayout when async font loading resolves. If using async fonts or other dynamic text layout, you are responsible for invalidating layout on changes.

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layout
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.sp

val textMeasurer = rememberTextMeasurer()
var textLayoutResult by remember {
    mutableStateOf<TextLayoutResult?>(null)
}

Canvas(
    Modifier
        .fillMaxSize()
        .layout { measurable, constraints ->
            val placeable = measurable.measure(constraints)
            // TextLayout can be done any time prior to its use in draw, including in a
            // background thread.
            // In this sample, text layout is measured in layout modifier. This way the layout
            // call can be restarted when async font loading completes due to the fact that
            // `.measure` call is executed in `.layout`.
            textLayoutResult = textMeasurer.measure(
                text = "Hello, World!",
                style = TextStyle(fontSize = 24.sp)
            )
            layout(placeable.width, placeable.height) {
                placeable.placeRelative(0, 0)
            }
        }) {
    // This happens during draw phase.
    textLayoutResult?.let { drawText(it) }
}
import androidx.compose.animation.animateColor
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.LocalTextStyle
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layout
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints

// We can disable implicit caching since we will cache in DrawWithCache
val textMeasurer = rememberTextMeasurer(cacheSize = 0)
// Apply the current text style from theme, otherwise TextStyle.Default will be used.
val materialTextStyle = LocalTextStyle.current

// Animate color repeatedly
val infiniteTransition = rememberInfiniteTransition()
val color by infiniteTransition.animateColor(
    initialValue = Color.Red,
    targetValue = Color.Blue,
    animationSpec = infiniteRepeatable(tween(1000))
)

Box(
    Modifier
        .fillMaxSize()
        .drawWithCache {
            // Text layout will be measured just once until the size of the drawing area or
            // materialTextStyle changes.
            val textLayoutResult = textMeasurer.measure(
                text = "Hello, World!",
                style = materialTextStyle,
                constraints = Constraints.fixed(
                    width = (size.width / 2).roundToInt(),
                    height = (size.height / 2).roundToInt()
                ),
                overflow = TextOverflow.Ellipsis
            )
            // color changes will only invalidate draw phase
            onDrawWithContent {
                drawContent()
                drawText(
                    textLayoutResult,
                    color = color,
                    topLeft = Offset(
                        (size.width - textLayoutResult.size.width) / 2,
                        (size.height - textLayoutResult.size.height) / 2,
                    )
                )
            }
        })
Parameters
@NonNull TextLayoutResult textLayoutResult

Text Layout to be drawn

@NonNull Color color

Text color to use

@NonNull Offset topLeft

Offsets the text from top left point of the current coordinate system.

float alpha

opacity to be applied to the color from 0.0f to 1.0f representing fully transparent to fully opaque respectively

Shadow shadow

The shadow effect applied on the text.

TextDecoration textDecoration

The decorations to paint on the text (e.g., an underline).

DrawStyle drawStyle

Whether or not the text is stroked or filled in.

@NonNull BlendMode blendMode

Blending algorithm to be applied to the text

TextPainterKt.drawText

default final void TextPainterKt.drawText(
    @NonNull DrawScope receiver,
    @NonNull TextMeasurer textMeasurer,
    @NonNull String text,
    @NonNull Offset topLeft,
    @NonNull TextStyle style,
    @NonNull TextOverflow overflow,
    boolean softWrap,
    int maxLines,
    @NonNull Size size,
    @NonNull BlendMode blendMode
)

Draw text using a TextMeasurer.

This draw function supports only one text style, and async font loading.

TextMeasurer carries an internal cache to optimize text layout measurement for repeated calls in draw phase. If layout affecting attributes like font size, font weight, overflow, softWrap, etc. are changed in consecutive calls to this method, TextMeasurer and its internal cache that holds layout results may not offer any benefits. Check out TextMeasurer and drawText overloads that take TextLayoutResult to learn more about text layout and draw phase optimizations.

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer

val textMeasurer = rememberTextMeasurer()

Canvas(Modifier.fillMaxSize()) {
    drawText(textMeasurer, "Hello, World!")
}
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.sp

val textMeasurer = rememberTextMeasurer()

Canvas(Modifier.fillMaxSize()) {
    drawText(
        textMeasurer = textMeasurer,
        text = "Hello, World!",
        style = TextStyle(
            fontSize = 24.sp,
            fontWeight = FontWeight.Bold,
            textDecoration = TextDecoration.Underline
        )
    )
}
Parameters
@NonNull TextMeasurer textMeasurer

Measures and lays out the text

@NonNull String text

Text to be drawn

@NonNull Offset topLeft

Offsets the text from top left point of the current coordinate system.

@NonNull TextStyle style

the TextStyle to be applied to the text

@NonNull TextOverflow overflow

How visual overflow should be handled.

boolean softWrap

Whether the text should break at soft line breaks. If false, the glyphs in the text will be positioned as if there was unlimited horizontal space. If softWrap is false, overflow and TextAlign may have unexpected effects.

int maxLines

An optional maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be truncated according to overflow and softWrap. If it is not null, then it must be greater than zero.

@NonNull Size size

how wide and tall the text should be. If left Size.Unspecified as its default value, text will be forced to fit inside the total drawing area from where it's placed. If size is specified, Size.width will define the width of the text. Size.height helps defining the number of lines that fit if softWrap is enabled and overflow is TextOverflow.Ellipsis. Otherwise, Size.height either defines where the text is clipped (TextOverflow.Clip) or becomes no-op.

@NonNull BlendMode blendMode

Blending algorithm to be applied to the text

TextPainterKt.drawText

default final void TextPainterKt.drawText(
    @NonNull DrawScope receiver,
    @NonNull TextMeasurer textMeasurer,
    @NonNull AnnotatedString text,
    @NonNull Offset topLeft,
    @NonNull TextStyle style,
    @NonNull TextOverflow overflow,
    boolean softWrap,
    int maxLines,
    @NonNull List<@NonNull AnnotatedString.Range<@NonNull Placeholder>> placeholders,
    @NonNull Size size,
    @NonNull BlendMode blendMode
)

Draw styled text using a TextMeasurer.

This draw function supports multi-styling and async font loading.

TextMeasurer carries an internal cache to optimize text layout measurement for repeated calls in draw phase. If layout affecting attributes like font size, font weight, overflow, softWrap, etc. are changed in consecutive calls to this method, TextMeasurer and its internal cache that holds layout results may not offer any benefits. Check out TextMeasurer and drawText overloads that take TextLayoutResult to learn more about text layout and draw phase optimizations.

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.ParagraphStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle

val textMeasurer = rememberTextMeasurer()

Canvas(Modifier.fillMaxSize()) {
    drawText(
        textMeasurer = textMeasurer,
        text = buildAnnotatedString {
            withStyle(ParagraphStyle(textAlign = TextAlign.Start)) {
                append("Hello")
            }
            withStyle(ParagraphStyle(textAlign = TextAlign.End)) {
                append("World")
            }
        }
    )
}
Parameters
@NonNull TextMeasurer textMeasurer

Measures and lays out the text

@NonNull AnnotatedString text

Text to be drawn

@NonNull Offset topLeft

Offsets the text from top left point of the current coordinate system.

@NonNull TextStyle style

the TextStyle to be applied to the text

@NonNull TextOverflow overflow

How visual overflow should be handled.

boolean softWrap

Whether the text should break at soft line breaks. If false, the glyphs in the text will be positioned as if there was unlimited horizontal space. If softWrap is false, overflow and TextAlign may have unexpected effects.

int maxLines

An optional maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be truncated according to overflow and softWrap. If it is not null, then it must be greater than zero.

@NonNull List<@NonNull AnnotatedString.Range<@NonNull Placeholder>> placeholders

a list of Placeholders that specify ranges of text which will be skipped during layout and replaced with Placeholder. It's required that the range of each Placeholder doesn't cross paragraph boundary, otherwise IllegalArgumentException is thrown.

@NonNull Size size

how wide and tall the text should be. If left Size.Unspecified as its default value, text will be forced to fit inside the total drawing area from where it's placed. If size is specified, Size.width will define the width of the text. Size.height helps defining the number of lines that fit if softWrap is enabled and overflow is TextOverflow.Ellipsis. Otherwise, Size.height either defines where the text is clipped (TextOverflow.Clip) or becomes no-op.

@NonNull BlendMode blendMode

Blending algorithm to be applied to the text