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 |
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 ( |
Cmn
|
ImageBitmap |
Graphics object that represents a 2 dimensional array of pixel information represented as ARGB values |
Cmn
|
Interpolatable |
Represents an object which may be able to be linearly interpolated with another object. |
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 |
Cmn
|
PathMeasure |
Cmn
|
|
Shape |
Defines a generic shape. |
Cmn
|
Classes
AndroidPaint |
Create a Compose |
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 |
|
Cmn
android
|
Brush |
Cmn
|
|
CanvasHolder |
Holder class that is used to issue scoped calls to a |
android
|
ClipOp |
Defines how a new clip region should be merged with the existing clip region. |
Cmn
|
Color |
The |
Cmn
|
ColorFilter |
Effect used to modify the color of each pixel drawn on a |
Cmn
|
ColorMatrix |
4x5 matrix for transforming the color and alpha components of a source. |
Cmn
|
ColorMatrixColorFilter |
Create a |
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 |
Cmn
|
LinearGradient |
Brush implementation used to apply a linear gradient on a given |
Cmn
|
Matrix |
Cmn
|
|
NativeCanvas |
Cmn
android
|
|
NativeColorFilter |
Cmn
|
|
NativePaint |
Cmn
android
|
|
OffsetEffect |
|
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 |
Cmn
|
PathHitTester |
A |
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 |
Cmn
|
PixelMap |
Result of a pixel read operation. |
Cmn
|
PointMode |
Used by |
Cmn
|
RadialGradient |
Brush implementation used to apply a radial gradient on a given |
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 |
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 |
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 |
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 |
Cmn
|
PathSegment.Type |
Type of a given segment in a |
Cmn
|
Type aliases
NativeCanvas |
android
|
|
NativePaint |
android
|
|
Shader |
android
|
Constants summary
const Float |
DefaultAlpha = 1.0fDefault alpha value used on |
Cmn
|
const Float |
DefaultCameraDistance = 8.0fDefault camera distance for all layers |
Cmn
|
Top-level functions summary
BlurEffect |
BlurEffect(radiusX: Float, radiusY: Float, edgeTreatment: TileMode)Create a |
Cmn
|
Canvas |
android
|
|
Canvas |
Canvas(image: ImageBitmap)Create a new Canvas instance that targets its drawing commands to the provided |
Cmn
|
Color |
Creates a new |
Cmn
|
Color |
Creates a new |
Cmn
|
Color |
Color(Creates a new |
Cmn
|
Color |
Create a |
Cmn
|
Shader |
CompositeShader(dst: Shader, src: Shader, blendMode: BlendMode)Creates a composited result between 2 shaders and the specified BlendMode. |
Cmn
|
GraphicsContext |
GraphicsContext(layerContainer: ViewGroup)Create a new |
android
|
GraphicsLayerScope |
Creates simple |
Cmn
|
ImageBitmap |
ImageBitmap( |
Cmn
|
Shader |
ImageShader(image: ImageBitmap, tileModeX: TileMode, tileModeY: TileMode)Creates a Shader using the given |
Cmn
|
Shader |
LinearGradientShader(Creates a linear gradient from |
Cmn
|
OffsetEffect |
OffsetEffect(offsetX: Float, offsetY: Float)Create an |
Cmn
|
Paint |
Paint() |
Cmn
android
|
Path |
Path() |
Cmn
android
|
PathHitTester |
PathHitTester(path: Path, tolerance: @FloatRange(from = 0.0) Float)Creates a new |
Cmn
|
PathIterator |
PathIterator(A path iterator can be used to iterate over all the |
Cmn
android
|
PathMeasure |
Create an empty |
Cmn
android
|
Shader |
RadialGradientShader(Creates a radial gradient centered at |
Cmn
|
ShaderBrush |
ShaderBrush(shader: Shader)Convenience method to create a ShaderBrush that always returns the same shader instance regardless of size |
Cmn
|
Shader |
Creates a circular gradient that sweeps around a provided center point. |
Cmn
|
TransformOrigin |
TransformOrigin(pivotFractionX: Float, pivotFractionY: Float)Constructs a |
Cmn
|
Color |
lerp(Linear interpolate between two |
Cmn
|
Shadow |
Linearly interpolate two |
Cmn
|
GraphicsLayer |
@ComposableCreate a new |
Cmn
|
Extension functions summary
Unit |
Path.addOutline(outline: Outline) |
Cmn
|
Unit |
Cmn
|
|
Bitmap |
android
|
|
ColorFilter |
Obtain a |
android
|
inline Path |
android
|
|
PathEffect |
android
|
|
ColorFilter |
Create a |
android
|
Paint |
Convert an |
android
|
Path |
Convert the |
android
|
RenderEffect |
Convert the |
android
|
ImageBitmap |
Create an |
android
|
Color |
Color.compositeOver(background: Color)Composites |
Cmn
|
Path.Direction |
Computes this |
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> |
Path.divide(contours: MutableList<Path>)Divides this path into a list of paths. |
Cmn
|
Unit |
Canvas.drawOutline(outline: Outline, paint: Paint) |
Cmn
|
Unit |
DrawScope.drawOutline( |
Cmn
|
Unit |
DrawScope.drawOutline( |
Cmn
|
Color |
Color.Companion.fromColorLong(colorLong: @ColorLong Long)Creates a Color from an Android 64-bit color value. |
android
|
Modifier |
Modifier.graphicsLayer(block: GraphicsLayerScope.() -> Unit)A |
Cmn
|
Modifier |
Modifier.graphicsLayer(A |
Cmn
|
Boolean |
Whether the given matrix is the identity matrix. |
Cmn
|
Boolean |
Capability query to determine if the particular platform supports the |
Cmn
android
|
Boolean |
Capability query to determine if the particular platform supports the |
Cmn
android
|
Float |
Returns the relative luminance of this color. |
Cmn
|
Path |
Reverses the segments of this path into the specified |
Cmn
|
Unit |
Add a rotation (in degrees clockwise) to the current transform at the given pivot point. |
Cmn
|
Unit |
Add a rotation (in radians clockwise) to the current transform at the given pivot point. |
Cmn
|
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. |
Cmn
|
Unit |
Set the matrix values the native |
android
|
Unit |
Set the native |
android
|
inline Color |
Color.takeOrElse(block: () -> Color)If this color |
Cmn
|
ColorSpace |
@RequiresApi(value = 26)Convert the Compose |
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
|
RectF |
Creates a new instance of |
android
|
Shader.TileMode |
android
|
|
Canvas.VertexMode |
android
|
|
@ColorInt Int |
Converts this color to an ARGB color int. |
Cmn
|
@ColorLong Long |
Converts the Color to a 64-bit |
android
|
ColorSpace |
@RequiresApi(value = 26)Convert the |
android
|
IntRect |
Creates a new instance of |
android
|
PathEffect |
android
|
|
Rect |
Creates a new instance of |
android
|
Rect |
Creates a new instance of |
android
|
TileMode |
android
|
|
PixelMap |
ImageBitmap.toPixelMap(Convenience method to extract pixel information from the given ImageBitmap into a |
Cmn
|
String |
Returns an SVG representation of this path. |
Cmn
|
Modifier |
A |
Cmn
|
inline 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 |
Cmn
|
Color |
Default ambient shadow color for all layers. |
Cmn
|
PathSegment |
A |
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 |
|
Cmn
|
Boolean |
|
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(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.
| 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 |
| 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.
| Throws | |
|---|---|
kotlin.IllegalArgumentException |
If |
kotlin.IllegalArgumentException |
If |
CompositeShader
fun CompositeShader(dst: Shader, src: Shader, blendMode: BlendMode): Shader
Creates a composited result between 2 shaders and the specified BlendMode. The specified destination and source Shader inputs will be consumed as the source and destination images for the corresponding blending algorithm.
| Parameters | |
|---|---|
dst: Shader |
Shader used as the destination content |
src: Shader |
Shader used as the source content |
blendMode: BlendMode |
BlendMode used to composite the source against the destination shader |
| See also | |
|---|---|
BlendMode |
GraphicsContext
fun GraphicsContext(layerContainer: ViewGroup): GraphicsContext
Create a new GraphicsContext with the provided ViewGroup to contain View based layers.
| Parameters | |
|---|---|
layerContainer: ViewGroup |
|
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
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 |
tolerance: @FloatRange(from = 0.0) Float = 0.5f |
When |
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 |
conicEvaluation: PathIterator.ConicEvaluation = ConicEvaluation.AsQuadratics |
Indicates how to evaluate conic segments |
tolerance: Float = 0.25f |
When |
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
TransformOrigin
fun TransformOrigin(pivotFractionX: Float, pivotFractionY: Float): TransformOrigin
Constructs a TransformOrigin from the given fractional values from the Layer's width and height
lerp
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
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 |
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 |
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 |
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.
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 |
| Returns | |
|---|---|
MutableList<Path> |
A list of |
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 |
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 |
blendMode: BlendMode = DrawScope.DefaultBlendMode |
: Blending algorithm to be applied to the outline |
fromColorLong
fun Color.Companion.fromColorLong(colorLong: @ColorLong Long): Color
Creates a Color from an Android 64-bit color value. This differs from the Color constructor accepting a Long in that the constructor assumes the incoming value is a 32-bit ARGB color, while this is a 64-bit ColorLong color from Android. Color.value isn't fully compatible with Android's 64-bit ColorLong values as some color spaces differ, so this method handles the conversion.
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.
NOTE: block can be invoked multiple times, which is why it's important for performance to minimize work done inside of it. block may also be invoked before effects.
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 |
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,
blendMode: BlendMode = BlendMode.SrcOver,
colorFilter: ColorFilter? = null
): 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 |
|
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 |
|
blendMode: BlendMode = BlendMode.SrcOver |
|
colorFilter: ColorFilter? = null |
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.
luminance
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 |
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 |
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
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
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.
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
toArgb
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.
toColorLong
fun Color.toColorLong(): @ColorLong Long
Converts the Color to a 64-bit ColorLong value that can be used by Android's framework. Color.value isn't fully compatible with Android's 64-bit ColorLong values as some color spaces differ, so this method handles the conversion.
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 |
startY: Int = 0 |
The y-coordinate of the first pixel to read from the |
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 |
bufferOffset: Int = 0 |
The first index to write into the buffer array, this defaults to 0 |
stride: Int = width |
The number of entries in |
| 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:
-
Canvas.save, which saves the current state, but does not create a new layer for subsequent commands. -
BlendMode, which discusses the use ofPaint.blendModewith saveLayer.
Top-level properties
CloseSegment
val CloseSegment: PathSegment
A PathSegment containing the Close command. This static object exists to avoid allocating a new segment when returning a Close result from PathIterator.next.
DoneSegment
val DoneSegment: PathSegment
A PathSegment containing the Done command. This static object exists to avoid allocating a new segment when returning a Done result from PathIterator.next.
Extension properties
nativeCanvas
val Canvas.nativeCanvas: NativeCanvas
Return an instance of the native primitive that implements the Canvas interface