androidx.compose.ui.graphics

In this page, you'll find documentation for types, properties, and functions available in the androidx.compose.ui.graphics package such as Brush, Canvas, Color, ImageBitmap, Path, and Shape.

If you're looking for guidance instead, check out the Graphics in Compose guide.

Interfaces

Canvas
Cmn
ColorProducer

Alternative to () -> Color that's useful for avoiding boxing.

Cmn
GraphicsContext

Class responsible for providing graphics related dependencies.

Cmn
GraphicsLayerScope

A scope which can be used to define the effects to apply for the content, such as scaling (scaleX, scaleY), rotation (rotationX, rotationY, rotationZ), opacity (alpha), shadow (shadowElevation, shape), and clipping (clip, shape).

Cmn
ImageBitmap

Graphics object that represents a 2 dimensional array of pixel information represented as ARGB values

Cmn
Paint
Cmn
Path
Cmn
PathEffect

Effect applied to the geometry of a drawing primitive.

Cmn
PathIterator

A path iterator can be used to iterate over all the segments that make up a path.

Cmn
PathMeasure
Cmn
Shape

Defines a generic shape.

Cmn

Classes

AndroidPaint

Create a Compose Paint instance backed by an android.graphics.Paint object to be consumed by Compose applications running on the Android platform

android
AndroidPath
android
AndroidPathMeasure
android
BlendMode

Algorithms to use when painting on the canvas.

Cmn
BlendModeColorFilter

Creates a color filter that applies the blend mode given as the second argument.

Cmn
BlurEffect

RenderEffect that will blur the contents of an optional input RenderEffect.

Cmn
android
Brush
Cmn
CanvasHolder

Holder class that is used to issue scoped calls to a Canvas from the framework equivalent canvas without having to allocate an object on each draw call

android
ClipOp

Defines how a new clip region should be merged with the existing clip region.

Cmn
Color

The Color class contains color information to be used while painting in Canvas.

Cmn
ColorFilter

Effect used to modify the color of each pixel drawn on a Paint that it is installed on

Cmn
ColorMatrix

4x5 matrix for transforming the color and alpha components of a source.

Cmn
ColorMatrixColorFilter

Create a ColorFilter that transforms colors through a 4x5 color matrix.

Cmn
CompositingStrategy

Determines when to render the contents of a layer into an offscreen buffer before being drawn to the destination.

Cmn
FilterQuality

Quality levels for image filters.

Cmn
ImageBitmapConfig

Possible ImageBitmap configurations.

Cmn
LightingColorFilter

Create a ColorFilter that can be used to simulate simple lighting effects.

Cmn
LinearGradient

Brush implementation used to apply a linear gradient on a given Paint

Cmn
Matrix
Cmn
NativeCanvas
Cmn
android
NativeColorFilter
Cmn
NativePaint
Cmn
android
OffsetEffect

RenderEffect used to translate either the given RenderEffect or the content of the GraphicsLayerScope it is configured on.

Cmn
android
Outline

Defines a simple shape, used for bounding graphical regions.

Cmn
Outline.Generic

An area defined as a path.

Cmn
Outline.Rectangle

Rectangular area.

Cmn
Outline.Rounded

Rectangular area with rounded corners.

Cmn
PaintingStyle

Strategies for painting shapes and paths on a canvas.

Cmn
PathFillType

Determines the winding rule that decides how the interior of a Path is calculated.

Cmn
PathHitTester

A PathHitTester is used to query whether certain x/y coordinates lie inside a given Path.

Cmn
PathOperation

Strategies for combining paths.

Cmn
PathSegment

A path segment represents a curve (line, cubic, quadratic or conic) or a command inside a fully formed Path object.

Cmn
PixelMap

Result of a pixel read operation.

Cmn
PointMode

Used by Canvas.drawPoints.

Cmn
RadialGradient

Brush implementation used to apply a radial gradient on a given Paint

Cmn
RenderEffect

Intermediate rendering step used to render drawing commands with a corresponding visual effect.

Cmn
android
Shader

Class that represents the corresponding Shader implementation on a platform.

Cmn
android
ShaderBrush

Brush implementation that wraps and applies a the provided shader to a Paint The shader can be lazily created based on a given size, or provided directly as a parameter

Cmn
Shadow

A single shadow.

Cmn
SolidColor
Cmn
StampedPathEffectStyle

Strategy for transforming each point of the shape along the drawn path

Cmn
StrokeCap

Styles to use for line endings.

Cmn
StrokeJoin

Styles to use for line joins.

Cmn
SweepGradient

Brush implementation used to apply a sweep gradient on a given Paint

Cmn
TileMode

Defines what happens at the edge of the gradient.

Cmn
TransformOrigin

A two-dimensional position represented as a fraction of the Layer's width and height

Cmn
VertexMode

Defines how a list of points is interpreted when drawing a set of triangles.

Cmn
Vertices

A set of vertex data used by Canvas.drawVertices.

Cmn

Objects

Color.Companion
Cmn
ImageBitmap.Companion

Provide an empty companion object to hang platform-specific companion extensions onto.

Cmn
PathOperation.Companion
Cmn

Annotations

Enums

Path.Direction

Specifies how closed shapes (e.g. rectangles, ovals) are wound (oriented) when they are added to a path.

Cmn
PathIterator.ConicEvaluation

Used to define how conic segments are evaluated when iterating over a Path using PathIterator.

Cmn
PathSegment.Type

Type of a given segment in a Path, either a command (Type.Move, Type.Close, Type.Done) or a curve (Type.Line, Type.Cubic, Type.Quadratic, Type.Conic).

Cmn

Type aliases

NativeCanvas
android
NativePaint
android
Shader
android

Constants summary

const Float

Default alpha value used on Paint.

Cmn
const Float

Default camera distance for all layers

Cmn

Top-level functions summary

BlurEffect
BlurEffect(radiusX: Float, radiusY: Float, edgeTreatment: TileMode)

Create a BlurEffect that implicitly blurs the contents of the GraphicsLayerScope it is configured on

Cmn
Canvas
android
Canvas

Create a new Canvas instance that targets its drawing commands to the provided ImageBitmap

Cmn
Color
Color(color: @ColorInt Int)

Creates a new Color instance from an ARGB color int.

Cmn
Color
Color(color: Long)

Creates a new Color instance from an ARGB color int.

Cmn
Color
Color(
    red: @IntRange(from = 0, to = 255) Int,
    green: @IntRange(from = 0, to = 255) Int,
    blue: @IntRange(from = 0, to = 255) Int,
    alpha: @IntRange(from = 0, to = 255) Int
)

Creates a new Color instance from an ARGB color components.

Cmn
Color
Color(
    red: Float,
    green: Float,
    blue: Float,
    alpha: Float,
    colorSpace: ColorSpace
)

Create a Color by passing individual red, green, blue, alpha, and colorSpace components.

Cmn
GraphicsContext
GraphicsContext(layerContainer: ViewGroup)

Create a new GraphicsContext with the provided ViewGroup to contain View based layers.

android
GraphicsLayerScope

Creates simple GraphicsLayerScope.

Cmn
ImageBitmap
ImageBitmap(
    width: Int,
    height: Int,
    config: ImageBitmapConfig,
    hasAlpha: Boolean,
    colorSpace: ColorSpace
)
Cmn
Shader
ImageShader(image: ImageBitmap, tileModeX: TileMode, tileModeY: TileMode)

Creates a Shader using the given ImageBitmap as an input texture.

Cmn
Shader
LinearGradientShader(
    from: Offset,
    to: Offset,
    colors: List<Color>,
    colorStops: List<Float>?,
    tileMode: TileMode
)

Creates a linear gradient from from to to.

Cmn
OffsetEffect
OffsetEffect(offsetX: Float, offsetY: Float)

Create an OffsetEffect that implicitly offsets the contents of the GraphicsLayerScope it is configured on

Cmn
Paint
Cmn
android
Path
Cmn
android
PathHitTester
PathHitTester(path: Path, tolerance: @FloatRange(from = 0.0) Float)

Creates a new PathHitTester to query whether certain x/y coordinates lie inside a given Path.

Cmn
PathIterator
PathIterator(
    path: Path,
    conicEvaluation: PathIterator.ConicEvaluation,
    tolerance: Float
)

A path iterator can be used to iterate over all the segments that make up a path.

Cmn
android
PathMeasure

Create an empty PathMeasure object.

Cmn
android
Shader
RadialGradientShader(
    center: Offset,
    radius: Float,
    colors: List<Color>,
    colorStops: List<Float>?,
    tileMode: TileMode
)

Creates a radial gradient centered at center that ends at radius distance from the center.

Cmn
ShaderBrush

Convenience method to create a ShaderBrush that always returns the same shader instance regardless of size

Cmn
Shader
SweepGradientShader(
    center: Offset,
    colors: List<Color>,
    colorStops: List<Float>?
)

Creates a circular gradient that sweeps around a provided center point.

Cmn
TransformOrigin
TransformOrigin(pivotFractionX: Float, pivotFractionY: Float)

Constructs a TransformOrigin from the given fractional values from the Layer's width and height

Cmn
Color
lerp(
    start: Color,
    stop: Color,
    fraction: @FloatRange(from = 0.0, to = 1.0) Float
)

Linear interpolate between two Colors, start and stop with fraction fraction between the two.

Cmn
Shadow
lerp(start: Shadow, stop: Shadow, fraction: Float)

Linearly interpolate two Shadows.

Cmn
GraphicsLayer

Create a new GraphicsLayer instance that will automatically be released when the Composable is disposed.

Cmn

Extension functions summary

Unit

Adds the outline to the Path.

Cmn
Unit
Path.addSvg(pathData: String)

Adds the specified SVG path data to this Path.

Cmn
Bitmap
android
ColorFilter

Obtain a android.graphics.ColorFilter instance from this ColorFilter

android
inline Path
android
PathEffect
android
ColorFilter

Create a ColorFilter from the given android.graphics.ColorFilter instance

android
Paint

Convert an android.graphics.Paint instance into a Compose-compatible Paint

android
Path

Convert the android.graphics.Path instance into a Compose-compatible Path

android
RenderEffect

Convert the android.graphics.RenderEffect instance into a Compose-compatible RenderEffect

android
ImageBitmap

Create an ImageBitmap from the given Bitmap.

android
Color
Color.compositeOver(background: Color)

Composites this color on top of background using the Porter-Duff 'source over' mode.

Cmn
Path.Direction

Computes this Path's direction (or winding, or orientation), which can be either Path.Direction.Clockwise or Path.Direction.CounterClockwise.

Cmn
Path

Create a new path, copying the contents from the src path.

Cmn
ImageBitmap

Decodes a byte array of a Bitmap to an ImageBitmap.

Cmn
MutableList<Path>

Divides this path into a list of paths.

Cmn
Unit
Canvas.drawOutline(outline: Outline, paint: Paint)

Draws the Outline on a Canvas.

Cmn
Unit
DrawScope.drawOutline(
    outline: Outline,
    brush: Brush,
    alpha: @FloatRange(from = 0.0, to = 1.0) Float,
    style: DrawStyle,
    colorFilter: ColorFilter?,
    blendMode: BlendMode
)

Draws the Outline on a DrawScope.

Cmn
Unit
DrawScope.drawOutline(
    outline: Outline,
    color: Color,
    alpha: @FloatRange(from = 0.0, to = 1.0) Float,
    style: DrawStyle,
    colorFilter: ColorFilter?,
    blendMode: BlendMode
)

Draws the Outline on a DrawScope.

Cmn
Modifier

A Modifier.Node that makes content draw into a draw layer.

Cmn
Modifier
Modifier.graphicsLayer(
    scaleX: Float,
    scaleY: Float,
    alpha: Float,
    translationX: Float,
    translationY: Float,
    shadowElevation: Float,
    rotationX: Float,
    rotationY: Float,
    rotationZ: Float,
    cameraDistance: Float,
    transformOrigin: TransformOrigin,
    shape: Shape,
    clip: Boolean,
    renderEffect: RenderEffect?,
    ambientShadowColor: Color,
    spotShadowColor: Color,
    compositingStrategy: CompositingStrategy
)

A Modifier.Element that makes content draw into a draw layer.

Cmn
Boolean

Whether the given matrix is the identity matrix.

Cmn
Boolean

Capability query to determine if the particular platform supports the BlendMode.

Cmn
android
Boolean

Capability query to determine if the particular platform supports the TileMode.

Cmn
android
Float

Returns the relative luminance of this color.

Cmn
Path
Path.reverse(destination: Path)

Reverses the segments of this path into the specified destination, turning a clockwise path into a counter-clockwise path and vice-versa.

Cmn
Unit
Canvas.rotate(degrees: Float, pivotX: Float, pivotY: Float)

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

Cmn
Unit
Canvas.rotateRad(radians: Float, pivotX: Float, pivotY: Float)

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

Cmn
Unit
Canvas.scale(sx: Float, sy: Float, pivotX: Float, pivotY: Float)

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.

Cmn
Unit

Set the matrix values the native android.graphics.Matrix.

android
Unit

Set the native android.graphics.Matrix from matrix.

android
inline Color
Color.takeOrElse(block: () -> Color)

If this color isSpecified then this is returned, otherwise block is executed and its result is returned.

Cmn
ColorSpace

Convert the Compose ColorSpace into an Android framework android.graphics.ColorSpace

android
Rect

This function is deprecated. Converting Rect to android.graphics.Rect is lossy, and requires rounding.

android
Rect

Creates a new instance of android.graphics.Rect with the same bounds specified in the given IntRect

android
RectF

Creates a new instance of android.graphics.RectF with the same bounds specified in the given Rect

android
Shader.TileMode
android
Canvas.VertexMode
android
@ColorInt Int

Converts this color to an ARGB color int.

Cmn
ColorSpace

Convert the android.graphics.ColorSpace into a Compose ColorSpace

android
IntRect

Creates a new instance of androidx.compose.ui.unit.IntRect with the same bounds specified in the given android.graphics.Rect

android
PathEffect
android
Rect

Creates a new instance of androidx.compose.ui.geometry.Rect with the same bounds specified in the given android.graphics.Rect

android
Rect

Creates a new instance of androidx.compose.ui.geometry.Rect with the same bounds specified in the given android.graphics.RectF.

android
TileMode
android
PixelMap
ImageBitmap.toPixelMap(
    startX: Int,
    startY: Int,
    width: Int,
    height: Int,
    buffer: IntArray,
    bufferOffset: Int,
    stride: Int
)

Convenience method to extract pixel information from the given ImageBitmap into a PixelMap that supports for querying pixel information based on

Cmn
String
Path.toSvg(asDocument: Boolean)

Returns an SVG representation of this path.

Cmn
Modifier

A Modifier.Element that adds a draw layer such that tooling can identify an element in the drawn image.

Cmn
inline Unit
Canvas.withSave(block: () -> Unit)

Saves a copy of the current transform and clip on the save stack and executes the provided lambda with the current transform applied.

Cmn
inline Unit
Canvas.withSaveLayer(bounds: Rect, paint: Paint, block: () -> Unit)

Saves a copy of the current transform and clip on the save stack, and then creates a new group which subsequent calls will become a part of.

Cmn

Top-level properties summary

PathSegment

A PathSegment containing the Close command.

Cmn
Color

Default ambient shadow color for all layers.

Cmn
PathSegment

A PathSegment containing the Done command.

Cmn
Shape

A shape describing the rectangle.

Cmn

Extension properties summary

PathOperation

This property is deprecated. Use PathOperation.Difference instead

Cmn
PathOperation

This property is deprecated. Use PathOperation.Intersect instead

Cmn
Boolean

false when this is Color.Unspecified.

Cmn
Boolean

true when this is Color.Unspecified.

Cmn
NativeCanvas

Return an instance of the native primitive that implements the Canvas interface

Cmn
android
PathOperation

This property is deprecated. Use PathOperation.ReverseDifference instead

Cmn
PathOperation

This property is deprecated. Use PathOperation.Union instead

Cmn
PathOperation

This property is deprecated. Use PathOperation.Xor instead

Cmn

Constants

DefaultAlpha

const val DefaultAlpha = 1.0f: Float

Default alpha value used on Paint. This value will draw source content fully opaque.

DefaultCameraDistance

const val DefaultCameraDistance = 8.0f: Float

Default camera distance for all layers

Top-level functions

BlurEffect

fun BlurEffect(
    radiusX: Float,
    radiusY: Float,
    edgeTreatment: TileMode = TileMode.Clamp
): BlurEffect

Create a BlurEffect that implicitly blurs the contents of the GraphicsLayerScope it is configured on

Canvas

fun Canvas(c: Canvas): Canvas

Canvas

fun Canvas(image: ImageBitmap): Canvas

Create a new Canvas instance that targets its drawing commands to the provided ImageBitmap

Color

fun Color(color: @ColorInt Int): Color

Creates a new Color instance from an ARGB color int. The resulting color is in the sRGB color space.

Parameters
color: @ColorInt Int

The ARGB color int to create a Color from.

Returns
Color

A non-null instance of {@link Color}

Color

fun Color(color: Long): Color

Creates a new Color instance from an ARGB color int. The resulting color is in the sRGB color space. This is useful for specifying colors with alpha greater than 0x80 in numeric form without using Long.toInt:

val color = Color(0xFF000080)
Parameters
color: Long

The 32-bit ARGB color int to create a Color from

Returns
Color

A non-null instance of {@link Color}

Color

fun Color(
    red: @IntRange(from = 0, to = 255) Int,
    green: @IntRange(from = 0, to = 255) Int,
    blue: @IntRange(from = 0, to = 255) Int,
    alpha: @IntRange(from = 0, to = 255) Int = 255
): Color

Creates a new Color instance from an ARGB color components. The resulting color is in the sRGB color space. The default alpha value is 0xFF (opaque).

Parameters
red: @IntRange(from = 0, to = 255) Int

The red component of the color, between 0 and 255.

green: @IntRange(from = 0, to = 255) Int

The green component of the color, between 0 and 255.

blue: @IntRange(from = 0, to = 255) Int

The blue component of the color, between 0 and 255.

alpha: @IntRange(from = 0, to = 255) Int = 255

The alpha component of the color, between 0 and 255.

Returns
Color

A non-null instance of {@link Color}

Color

fun Color(
    red: Float,
    green: Float,
    blue: Float,
    alpha: Float = 1.0f,
    colorSpace: ColorSpace = ColorSpaces.Srgb
): Color

Create a Color by passing individual red, green, blue, alpha, and colorSpace components. The default color space is sRGB and the default alpha is 1.0 (opaque).

If the red, green, or blue values are outside of the range defined by colorSpace (see ColorSpace.getMinValue and ColorSpace.getMaxValue, these values get clamped appropriately to be within range.

GraphicsContext

fun GraphicsContext(layerContainer: ViewGroup): GraphicsContext

Create a new GraphicsContext with the provided ViewGroup to contain View based layers.

Parameters
layerContainer: ViewGroup

ViewGroup used to contain View based layers that are created by the returned GraphicsContext

GraphicsLayerScope

fun GraphicsLayerScope(): GraphicsLayerScope

Creates simple GraphicsLayerScope.

ImageBitmap

fun ImageBitmap(
    width: Int,
    height: Int,
    config: ImageBitmapConfig = ImageBitmapConfig.Argb8888,
    hasAlpha: Boolean = true,
    colorSpace: ColorSpace = ColorSpaces.Srgb
): ImageBitmap

ImageShader

fun ImageShader(
    image: ImageBitmap,
    tileModeX: TileMode = TileMode.Clamp,
    tileModeY: TileMode = TileMode.Clamp
): Shader

Creates a Shader using the given ImageBitmap as an input texture. If the shader is to be drawn in an area larger than the size of the ImageBitmap, the region is filled in the horizontal and vertical directions based on the tileModeX and tileModeY parameters.

LinearGradientShader

fun LinearGradientShader(
    from: Offset,
    to: Offset,
    colors: List<Color>,
    colorStops: List<Float>? = null,
    tileMode: TileMode = TileMode.Clamp
): Shader

Creates a linear gradient from from to to.

If colorStops is provided, each value is a number from 0.0 to 1.0 that specifies where the color at the corresponding index in colors begins in the gradient. If colorStops is not provided, then the colors are dispersed evenly

The behavior before from and after to is described by the tileMode argument. For details, see the TileMode enum. If no TileMode is provided the default value of TileMode.Clamp is used

OffsetEffect

fun OffsetEffect(offsetX: Float, offsetY: Float): OffsetEffect

Create an OffsetEffect that implicitly offsets the contents of the GraphicsLayerScope it is configured on

Paint

fun Paint(): Paint

Path

fun Path(): Path

PathHitTester

fun PathHitTester(path: Path, tolerance: @FloatRange(from = 0.0) Float = 0.5f): PathHitTester

Creates a new PathHitTester to query whether certain x/y coordinates lie inside a given Path. A PathHitTester is optimized to perform multiple queries against a single path.

The result of a query depends on the fill type of the path.

If the content of path changes, you must call PathHitTester.updatePath or create a new PathHitTester as PathHitTester will cache precomputed values to speed up queries.

If path contains conic curves, they are converted to quadratic curves during the query process. The tolerance of that conversion is defined by tolerance. The tolerance should be appropriate to the coordinate systems used by the caller. For instance if the path is defined in pixels, 0.5 (half a pixel) or 1.0 (a pixel) are appropriate tolerances. If the path is normalized and defined in the domain 0..1, the caller should choose a more appropriate tolerance close to or equal to one "query unit". The tolerance must be >= 0.

Parameters
path: Path

The Path to run queries against.

tolerance: @FloatRange(from = 0.0) Float = 0.5f

When path contains conic curves, defines the maximum distance between the original conic curve and its quadratic approximations. Set to 0.5 by default.

PathIterator

fun PathIterator(
    path: Path,
    conicEvaluation: PathIterator.ConicEvaluation = ConicEvaluation.AsQuadratics,
    tolerance: Float = 0.25f
): PathIterator

A path iterator can be used to iterate over all the segments that make up a path. Those segments may in turn define multiple contours inside the path. Conic segments are by default evaluated as approximated quadratic segments. To preserve conic segments as conics, set conicEvaluation to AsConic. The error of the approximation is controlled by tolerance.

A PathIterator can be created implicitly through a given Path object: using one of the two Path.iterator functions.

Parameters
path: Path

The Path to iterate over

conicEvaluation: PathIterator.ConicEvaluation = ConicEvaluation.AsQuadratics

Indicates how to evaluate conic segments

tolerance: Float = 0.25f

When conicEvaluation is set to PathIterator.ConicEvaluation.AsQuadratics defines the maximum distance between the original conic curve and its quadratic approximations

PathMeasure

fun PathMeasure(): PathMeasure

Create an empty PathMeasure object. To uses this to measure the length of a path, and/or to find the position and tangent along it, call PathMeasure.setPath. Note that once a path is associated with the measure object, it is undefined if the path is subsequently modified and the measure object is used. If the path is modified, you must call PathMeasure.setPath with the path.

RadialGradientShader

fun RadialGradientShader(
    center: Offset,
    radius: Float,
    colors: List<Color>,
    colorStops: List<Float>? = null,
    tileMode: TileMode = TileMode.Clamp
): Shader

Creates a radial gradient centered at center that ends at radius distance from the center.

If colorStops is provided, each value is a number from 0.0 to 1.0 that specifies where the color at the corresponding index in colors begins in the gradient. If colorStops is not provided, then the colors are dispersed evenly

The behavior before and after the radius is described by the tileMode argument. For details, see the TileMode enum.

The behavior outside of the bounds of center +/- radius is described by the tileMode argument. For details, see the TileMode enum. If no TileMode is provided the default value of TileMode.Clamp is used

ShaderBrush

fun ShaderBrush(shader: Shader): ShaderBrush

Convenience method to create a ShaderBrush that always returns the same shader instance regardless of size

SweepGradientShader

fun SweepGradientShader(
    center: Offset,
    colors: List<Color>,
    colorStops: List<Float>? = null
): Shader

Creates a circular gradient that sweeps around a provided center point. The sweep begins relative to 3 o'clock and continues clockwise until it reaches the starting position again.

If colorStops is provided, each value is a number from 0.0 to 1.0 that specifies where the color at the corresponding index in colors begins in the gradient. If colorStops is not provided, then the colors are dispersed evenly

Parameters
center: Offset

Position for the gradient to sweep around

colors: List<Color>

Colors to be rendered as part of the gradient

colorStops: List<Float>? = null

Placement of the colors along the sweep about the center position

TransformOrigin

fun TransformOrigin(pivotFractionX: Float, pivotFractionY: Float): TransformOrigin

Constructs a TransformOrigin from the given fractional values from the Layer's width and height

fun lerp(
    start: Color,
    stop: Color,
    fraction: @FloatRange(from = 0.0, to = 1.0) Float
): Color

Linear interpolate between two Colors, start and stop with fraction fraction between the two. The ColorSpace of the result is always the ColorSpace of stop. fraction should be between 0 and 1, inclusive. Interpolation is done in the ColorSpaces.Oklab color space.

lerp

fun lerp(start: Shadow, stop: Shadow, fraction: Float): Shadow

Linearly interpolate two Shadows.

rememberGraphicsLayer

@Composable
@ComposableOpenTarget(index = -1)
fun rememberGraphicsLayer(): GraphicsLayer

Create a new GraphicsLayer instance that will automatically be released when the Composable is disposed.

Returns
GraphicsLayer

a GraphicsLayer instance

Extension functions

addOutline

fun Path.addOutline(outline: Outline): Unit

Adds the outline to the Path.

addSvg

fun Path.addSvg(pathData: String): Unit

Adds the specified SVG path data to this Path. The SVG path data encodes a series of instructions that will be applied to this path. For instance, the following path data:

M200,300 Q400,50 600,300 L1000,300

Will generate the following series of instructions for this path:

moveTo(200f, 300f)
quadraticTo(400f, 50f, 600f, 300f)
lineTo(1000f, 300f)

To convert a Path to its SVG path data representation, please refer to Path.toSvg.

Throws
kotlin.IllegalArgumentException

if the path data contains an invalid instruction

See also
toSvg

asAndroidBitmap

fun ImageBitmap.asAndroidBitmap(): Bitmap
Throws
kotlin.UnsupportedOperationException

if this ImageBitmap is not backed by an android.graphics.Bitmap

asAndroidColorFilter

fun ColorFilter.asAndroidColorFilter(): ColorFilter

Obtain a android.graphics.ColorFilter instance from this ColorFilter

asAndroidPath

inline fun Path.asAndroidPath(): Path
Throws
kotlin.UnsupportedOperationException

if this Path is not backed by an android.graphics.Path.

asComposeColorFilter

fun ColorFilter.asComposeColorFilter(): ColorFilter

Create a ColorFilter from the given android.graphics.ColorFilter instance

asComposePaint

fun Paint.asComposePaint(): Paint

Convert an android.graphics.Paint instance into a Compose-compatible Paint

asComposePath

fun Path.asComposePath(): Path

Convert the android.graphics.Path instance into a Compose-compatible Path

asComposeRenderEffect

fun RenderEffect.asComposeRenderEffect(): RenderEffect

Convert the android.graphics.RenderEffect instance into a Compose-compatible RenderEffect

asImageBitmap

fun Bitmap.asImageBitmap(): ImageBitmap

Create an ImageBitmap from the given Bitmap. Note this does not create a copy of the original Bitmap and changes to it will modify the returned ImageBitmap

compositeOver

fun Color.compositeOver(background: Color): Color

Composites this color on top of background using the Porter-Duff 'source over' mode.

Both this and background must not be pre-multiplied, and the resulting color will also not be pre-multiplied.

The ColorSpace of the result is always the ColorSpace of background.

Returns
Color

the Color representing this composited on top of background, converted to the color space of background.

computeDirection

fun Path.computeDirection(): Path.Direction

Computes this Path's direction (or winding, or orientation), which can be either Path.Direction.Clockwise or Path.Direction.CounterClockwise.

If the path is made of multiple contours (the path contains multiple "move" commands), the direction returned by this property is the direction of the first contour.

If the path is empty (contains no lines/curves), the direction is Path.Direction.Clockwise.

If the path has no area (single straight line), the direction is Path.Direction.Clockwise.

Calling this property does not cache the result, the direction is computed Calling this method does not cache the result, the direction is computed every time the method is called.

If you need to query the direction of individual contours, you should divide the path first.

copy

fun Path.copy(): Path

Create a new path, copying the contents from the src path.

decodeToImageBitmap

fun ByteArray.decodeToImageBitmap(): ImageBitmap

Decodes a byte array of a Bitmap to an ImageBitmap.

Returns
ImageBitmap

The converted ImageBitmap.

divide

fun Path.divide(contours: MutableList<Path> = mutableListOf()): MutableList<Path>

Divides this path into a list of paths. Each contour inside this path is returned as a separate Path. For instance the following code snippet creates two rectangular contours:

val p = Path()
p.addRect(...)
p.addRect(...)

val contours = p.divide()

The list returned by calling p.divide() will contain two Path instances, each representing one of the two rectangles.

Empty contours (contours with no lines/curves) are omitted from the resulting list.

Parameters
contours: MutableList<Path> = mutableListOf()

An optional mutable list of Path that will hold the result of the division.

Returns
MutableList<Path>

A list of Path representing all the contours in this path. The returned list is either a newly allocated list if the contours parameter was left unspecified, or the contours parameter.

drawOutline

fun Canvas.drawOutline(outline: Outline, paint: Paint): Unit

Draws the Outline on a Canvas.

Parameters
outline: Outline

the outline to draw.

paint: Paint

the paint used for the drawing.

drawOutline

fun DrawScope.drawOutline(
    outline: Outline,
    brush: Brush,
    alpha: @FloatRange(from = 0.0, to = 1.0) Float = 1.0f,
    style: DrawStyle = Fill,
    colorFilter: ColorFilter? = null,
    blendMode: BlendMode = DrawScope.DefaultBlendMode
): Unit

Draws the Outline on a DrawScope.

Parameters
outline: Outline

the outline to draw.

brush: Brush

Brush applied to the outline when it is drawn

alpha: @FloatRange(from = 0.0, to = 1.0) Float = 1.0f

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

style: DrawStyle = Fill

Specifies whether the outline is stroked or filled in

colorFilter: ColorFilter? = null

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

blendMode: BlendMode = DrawScope.DefaultBlendMode

: Blending algorithm to be applied to the outline

drawOutline

fun DrawScope.drawOutline(
    outline: Outline,
    color: Color,
    alpha: @FloatRange(from = 0.0, to = 1.0) Float = 1.0f,
    style: DrawStyle = Fill,
    colorFilter: ColorFilter? = null,
    blendMode: BlendMode = DrawScope.DefaultBlendMode
): Unit

Draws the Outline on a DrawScope.

Parameters
outline: Outline

the outline to draw.

color: Color

Color applied to the outline when it is drawn

alpha: @FloatRange(from = 0.0, to = 1.0) Float = 1.0f

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

style: DrawStyle = Fill

Specifies whether the outline is stroked or filled in

colorFilter: ColorFilter? = null

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

blendMode: BlendMode = DrawScope.DefaultBlendMode

: Blending algorithm to be applied to the outline

graphicsLayer

fun Modifier.graphicsLayer(block: GraphicsLayerScope.() -> Unit): Modifier

A Modifier.Node that makes content draw into a draw layer. The draw layer can be invalidated separately from parents. A graphicsLayer should be used when the content updates independently from anything above it to minimize the invalidated content.

graphicsLayer can be used to apply effects to content, such as scaling, rotation, opacity, shadow, and clipping. Prefer this version when you have layer properties backed by a androidx.compose.runtime.State or an animated value as reading a state inside block will only cause the layer properties update without triggering recomposition and relayout.

import androidx.compose.animation.core.Animatable
import androidx.compose.material.Text
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer

val animatedAlpha = remember { Animatable(0f) }
Text(
    "Hello World",
    Modifier.graphicsLayer {
        alpha = animatedAlpha.value
        clip = true
    }
)
LaunchedEffect(animatedAlpha) { animatedAlpha.animateTo(1f) }
Parameters
block: GraphicsLayerScope.() -> Unit

block on GraphicsLayerScope where you define the layer properties.

graphicsLayer

fun Modifier.graphicsLayer(
    scaleX: Float = 1.0f,
    scaleY: Float = 1.0f,
    alpha: Float = 1.0f,
    translationX: Float = 0.0f,
    translationY: Float = 0.0f,
    shadowElevation: Float = 0.0f,
    rotationX: Float = 0.0f,
    rotationY: Float = 0.0f,
    rotationZ: Float = 0.0f,
    cameraDistance: Float = DefaultCameraDistance,
    transformOrigin: TransformOrigin = TransformOrigin.Center,
    shape: Shape = RectangleShape,
    clip: Boolean = false,
    renderEffect: RenderEffect? = null,
    ambientShadowColor: Color = DefaultShadowColor,
    spotShadowColor: Color = DefaultShadowColor,
    compositingStrategy: CompositingStrategy = CompositingStrategy.Auto
): Modifier

A Modifier.Element that makes content draw into a draw layer. The draw layer can be invalidated separately from parents. A graphicsLayer should be used when the content updates independently from anything above it to minimize the invalidated content.

graphicsLayer can also be used to apply effects to content, such as scaling (scaleX, scaleY), rotation (rotationX, rotationY, rotationZ), opacity (alpha), shadow (shadowElevation, shape), clipping (clip, shape), as well as altering the result of the layer with RenderEffect. Shadow color and ambient colors can be modified by configuring the spotShadowColor and ambientShadowColor respectively.

CompositingStrategy determines whether or not the contents of this layer are rendered into an offscreen buffer. This is useful in order to optimize alpha usages with CompositingStrategy.ModulateAlpha which will skip the overhead of an offscreen buffer but can generate different rendering results depending on whether or not the contents of the layer are overlapping. Similarly leveraging CompositingStrategy.Offscreen is useful in situations where creating an offscreen buffer is preferred usually in conjunction with BlendMode usage.

Note that if you provide a non-zero shadowElevation and if the passed shape is concave the shadow will not be drawn on Android versions less than 10.

Also note that alpha values less than 1.0f will have their contents implicitly clipped to their bounds unless CompositingStrategy.ModulateAlpha is specified. This is because an intermediate compositing layer is created to render contents into first before being drawn into the destination with the desired alpha. This layer is sized to the bounds of the composable this modifier is configured on, and contents outside of these bounds are omitted.

If the layer parameters are backed by a androidx.compose.runtime.State or an animated value prefer an overload with a lambda block on GraphicsLayerScope as reading a state inside the block will only cause the layer properties update without triggering recomposition and relayout.

import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer

Text("Hello World", Modifier.graphicsLayer(alpha = 0.5f, clip = true))
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.size
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.drawscope.inset
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.dp

Canvas(
    modifier =
        Modifier.size(100.dp)
            .background(Color.Black)
            .graphicsLayer(
                alpha = 0.5f,
                compositingStrategy = CompositingStrategy.ModulateAlpha
            )
) {
    // Configuring an alpha less than 1.0 and specifying
    // CompositingStrategy.ModulateAlpha ends up with the overlapping region
    // of the 2 draw rect calls to blend transparent blue and transparent red
    // against the black background instead of just transparent blue which is what would
    // occur with CompositingStrategy.Auto or CompositingStrategy.Offscreen
    inset(0f, 0f, size.width / 3, size.height / 3) { drawRect(color = Color.Red) }
    inset(size.width / 3, size.height / 3, 0f, 0f) { drawRect(color = Color.Blue) }
}
Parameters
scaleX: Float = 1.0f

see GraphicsLayerScope.scaleX

scaleY: Float = 1.0f

see GraphicsLayerScope.scaleY

alpha: Float = 1.0f

see GraphicsLayerScope.alpha

translationX: Float = 0.0f

see GraphicsLayerScope.translationX

translationY: Float = 0.0f

see GraphicsLayerScope.translationY

shadowElevation: Float = 0.0f

see GraphicsLayerScope.shadowElevation

rotationX: Float = 0.0f

see GraphicsLayerScope.rotationX

rotationY: Float = 0.0f

see GraphicsLayerScope.rotationY

rotationZ: Float = 0.0f

see GraphicsLayerScope.rotationZ

cameraDistance: Float = DefaultCameraDistance

see GraphicsLayerScope.cameraDistance

transformOrigin: TransformOrigin = TransformOrigin.Center

see GraphicsLayerScope.transformOrigin

shape: Shape = RectangleShape

see GraphicsLayerScope.shape

clip: Boolean = false

see GraphicsLayerScope.clip

renderEffect: RenderEffect? = null

see GraphicsLayerScope.renderEffect

ambientShadowColor: Color = DefaultShadowColor

see GraphicsLayerScope.ambientShadowColor

spotShadowColor: Color = DefaultShadowColor

see GraphicsLayerScope.spotShadowColor

compositingStrategy: CompositingStrategy = CompositingStrategy.Auto

see GraphicsLayerScope.compositingStrategy

isIdentity

fun Matrix.isIdentity(): Boolean

Whether the given matrix is the identity matrix.

isSupported

fun BlendMode.isSupported(): Boolean

Capability query to determine if the particular platform supports the BlendMode. Not all platforms support all blend mode algorithms, however, BlendMode.SrcOver is guaranteed to be supported as it is the default drawing algorithm. If a BlendMode that is not supported is used, the default of SrcOver is consumed instead.

isSupported

fun TileMode.isSupported(): Boolean

Capability query to determine if the particular platform supports the TileMode. Not all platforms support all tile mode algorithms, however, TileMode.Clamp, TileMode.Repeated and TileMode.Mirror are guaranteed to be supported. If a TileMode that is not supported is used, the default of TileMode.Clamp is consumed instead.

fun Color.luminance(): Float

Returns the relative luminance of this color.

Based on the formula for relative luminance defined in WCAG 2.0, W3C Recommendation 11 December 2008.

Returns
Float

A value between 0 (darkest black) and 1 (lightest white)

Throws
kotlin.IllegalArgumentException

If the this color's color space does not use the RGB color model

reverse

fun Path.reverse(destination: Path = Path()): Path

Reverses the segments of this path into the specified destination, turning a clockwise path into a counter-clockwise path and vice-versa. Each contour in the path is reversed independently, and the contours appear in the destination in reverse order.

This method preserves the general structure of this path as much as possible:

  • Lines become lines

  • Quadratic Bézier curves become quadratic Bézier curves

  • Cubic Bézier curves become cubic Bézier curves

  • Close and move commands remain close and move commands

  • Conic segments become quadratic Bézier curves

Returns
Path

A Path containing the reverse of this Path. The returned path is either a newly allocated Path if the destination parameter was left unspecified, or the destination parameter.

rotate

fun Canvas.rotate(degrees: Float, pivotX: Float, pivotY: Float): Unit

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

Parameters
degrees: Float

to rotate clockwise

pivotX: Float

The x-coord for the pivot point

pivotY: Float

The y-coord for the pivot point

rotateRad

fun Canvas.rotateRad(radians: Float, pivotX: Float = 0.0f, pivotY: Float = 0.0f): Unit

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
radians: Float

Rotation transform to apply to the Canvas

pivotX: Float = 0.0f

The x-coord for the pivot point

pivotY: Float = 0.0f

The y-coord for the pivot point

scale

fun Canvas.scale(sx: Float, sy: Float = sx, pivotX: Float, pivotY: Float): Unit

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.

If sy is unspecified, sx will be used for the scale in both directions.

Parameters
sx: Float

The amount to scale in X

sy: Float = sx

The amount to scale in Y

pivotX: Float

The x-coord for the pivot point

pivotY: Float

The y-coord for the pivot point

setFrom

fun Matrix.setFrom(matrix: Matrix): Unit

Set the matrix values the native android.graphics.Matrix.

setFrom

fun Matrix.setFrom(matrix: Matrix): Unit

Set the native android.graphics.Matrix from matrix.

takeOrElse

inline fun Color.takeOrElse(block: () -> Color): Color

If this color isSpecified then this is returned, otherwise block is executed and its result is returned.

toAndroidColorSpace

@RequiresApi(value = 26)
fun ColorSpace.toAndroidColorSpace(): ColorSpace

Convert the Compose ColorSpace into an Android framework android.graphics.ColorSpace

toAndroidRect

fun Rect.toAndroidRect(): Rect

Creates a new instance of android.graphics.Rect with the same bounds specified in the given Rect

toAndroidRect

fun IntRect.toAndroidRect(): Rect

Creates a new instance of android.graphics.Rect with the same bounds specified in the given IntRect

toAndroidRectF

fun Rect.toAndroidRectF(): RectF

Creates a new instance of android.graphics.RectF with the same bounds specified in the given Rect

fun Color.toArgb(): @ColorInt Int

Converts this color to an ARGB color int. A color int is always in the sRGB color space. This implies a color space conversion is applied if needed.

Returns
@ColorInt Int

An ARGB color in the sRGB color space

toComposeColorSpace

@RequiresApi(value = 26)
fun ColorSpace.toComposeColorSpace(): ColorSpace

Convert the android.graphics.ColorSpace into a Compose ColorSpace

toComposeIntRect

fun Rect.toComposeIntRect(): IntRect

Creates a new instance of androidx.compose.ui.unit.IntRect with the same bounds specified in the given android.graphics.Rect

toComposeRect

fun Rect.toComposeRect(): Rect

Creates a new instance of androidx.compose.ui.geometry.Rect with the same bounds specified in the given android.graphics.Rect

toComposeRect

fun RectF.toComposeRect(): Rect

Creates a new instance of androidx.compose.ui.geometry.Rect with the same bounds specified in the given android.graphics.RectF.

toPixelMap

fun ImageBitmap.toPixelMap(
    startX: Int = 0,
    startY: Int = 0,
    width: Int = this.width,
    height: Int = this.height,
    buffer: IntArray = IntArray(width * height),
    bufferOffset: Int = 0,
    stride: Int = width
): PixelMap

Convenience method to extract pixel information from the given ImageBitmap into a PixelMap that supports for querying pixel information based on

Note this method can block so it is recommended to not invoke this method in performance critical code paths

import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.PixelMap
import androidx.compose.ui.graphics.toPixelMap

val imageBitmap = createImageBitmap()

// Sample a 3 by 2 subsection of the given ImageBitmap
// starting at the coordinate (48, 49)
val pixelmap = imageBitmap.toPixelMap(startX = 48, startY = 49, width = 3, height = 2)

// create a histogram to count the number of occurrences of a color within the specified
// subsection of the provided ImageBitmap
val histogram = HashMap<Color, Int>()
for (x in 0 until pixelmap.width) {
    for (y in 0 until pixelmap.height) {
        val color = pixelmap[x, y]
        val colorCount = histogram[color] ?: 0
        histogram[color] = (colorCount + 1)
    }
}
Parameters
startX: Int = 0

The x-coordinate of the first pixel to read from the ImageBitmap

startY: Int = 0

The y-coordinate of the first pixel to read from the ImageBitmap

width: Int = this.width

The number of pixels to read from each row

height: Int = this.height

The number of rows to read

buffer: IntArray = IntArray(width * height)

The array to store the ImageBitmap's colors. By default this allocates an IntArray large enough to store all the pixel information. Consumers of this API are advised to use the smallest IntArray necessary to extract relevant pixel information

bufferOffset: Int = 0

The first index to write into the buffer array, this defaults to 0

stride: Int = width

The number of entries in buffer to skip between rows (must be >= width

See also
readPixels

toSvg

fun Path.toSvg(asDocument: Boolean = false): String

Returns an SVG representation of this path. The caller can choose whether the returned SVG represents a fully-formed SVG document or only the path data. By default, only the path data is returned which can be used either with Path.addSvg or androidx.compose.ui.graphics.vector.PathParser.

Parameters
asDocument: Boolean = false

When set to true, this function returns a fully-formed SVG document, otherwise returns only the path data.

See also
PathParser
addSvg

toolingGraphicsLayer

fun Modifier.toolingGraphicsLayer(): Modifier

A Modifier.Element that adds a draw layer such that tooling can identify an element in the drawn image.

withSave

inline fun Canvas.withSave(block: () -> Unit): Unit

Saves a copy of the current transform and clip on the save stack and executes the provided lambda with the current transform applied. Once the lambda has been executed, the transformation is popped from the stack, undoing the transformation.

See also:

Canvas.saveLayer, which does the same thing but additionally also groups the commands

withSaveLayer

inline fun Canvas.withSaveLayer(bounds: Rect, paint: Paint, block: () -> Unit): Unit

Saves a copy of the current transform and clip on the save stack, and then creates a new group which subsequent calls will become a part of. When the lambda is executed and the save stack is popped, the group will be flattened into a layer and have the given paint's Paint.colorFilter and Paint.blendMode applied.

This lets you create composite effects, for example making a group of drawing commands semi-transparent. Without using Canvas.saveLayer, each part of the group would be painted individually, so where they overlap would be darker than where they do not. By using Canvas.saveLayer to group them together, they can be drawn with an opaque color at first, and then the entire group can be made transparent using the Canvas.saveLayer's paint.

Using saveLayer with clips

When a rectangular clip operation (from Canvas.clipRect) is not axis-aligned with the raster buffer, or when the clip operation is not rectalinear (e.g. because it is a rounded rectangle clip created by Canvas.clipPath), the edge of the clip needs to be anti-aliased.

If two draw calls overlap at the edge of such a clipped region, without using Canvas.saveLayer, the first drawing will be anti-aliased with the background first, and then the second will be anti-aliased with the result of blending the first drawing and the background. On the other hand, if Canvas.saveLayer is used immediately after establishing the clip, the second drawing will cover the first in the layer, and thus the second alone will be anti-aliased with the background when the layer is clipped and composited (when lambda is finished executing).

Performance considerations

Generally speaking, Canvas.saveLayer is relatively expensive.

There are a several different hardware architectures for GPUs (graphics processing units, the hardware that handles graphics), but most of them involve batching commands and reordering them for performance. When layers are used, they cause the rendering pipeline to have to switch render target (from one layer to another). Render target switches can flush the GPU's command buffer, which typically means that optimizations that one could get with larger batching are lost. Render target switches also generate a lot of memory churn because the GPU needs to copy out the current frame buffer contents from the part of memory that's optimized for writing, and then needs to copy it back in once the previous render target (layer) is restored.

See also:

Top-level properties

CloseSegment

val CloseSegmentPathSegment

A PathSegment containing the Close command. This static object exists to avoid allocating a new segment when returning a Close result from PathIterator.next.

DefaultShadowColor

val DefaultShadowColorColor

Default ambient shadow color for all layers.

DoneSegment

val DoneSegmentPathSegment

A PathSegment containing the Done command. This static object exists to avoid allocating a new segment when returning a Done result from PathIterator.next.

RectangleShape

val RectangleShapeShape

A shape describing the rectangle.

Extension properties

difference

val PathOperation.Companion.differencePathOperation

intersect

val PathOperation.Companion.intersectPathOperation

isSpecified

val Color.isSpecifiedBoolean

false when this is Color.Unspecified.

isUnspecified

val Color.isUnspecifiedBoolean

true when this is Color.Unspecified.

nativeCanvas

val Canvas.nativeCanvasNativeCanvas

Return an instance of the native primitive that implements the Canvas interface

reverseDifference

val PathOperation.Companion.reverseDifferencePathOperation

union

val PathOperation.Companion.unionPathOperation

xor

val PathOperation.Companion.xorPathOperation