Canvas

The Canvas class holds the "draw" calls. To draw something, you need
4 basic components: A Bitmap to hold the pixels, a Canvas to host
the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect,
Path, text, Bitmap), and a paint (to describe the colors and styles for the
drawing).

This method was deprecated
in API level 21.
Usage with a hardware accelerated canvas
requires an internal copy of color buffer contents every time this method is called. Using a
Bitmap avoids this copy, and allows the application to more explicitly control the lifetime
and copies of pixel data.

This method was deprecated
in API level 21.
Usage with a hardware accelerated canvas
requires an internal copy of color buffer contents every time this method is called. Using a
Bitmap avoids this copy, and allows the application to more explicitly control the lifetime
and copies of pixel data.

This method was deprecated
in API level 16.
This method does not support glyph composition and decomposition and
should therefore not be used to render complex scripts. It also doesn't
handle supplementary characters (eg emoji).

This method was deprecated
in API level 16.
This method does not support glyph composition and decomposition and
should therefore not be used to render complex scripts. It also doesn't
handle supplementary characters (eg emoji).

This method was deprecated
in API level 16.
Hardware accelerated canvases may have any
matrix when passed to a View or Drawable, as it is implementation defined where in the
hierarchy such canvases are created. It is recommended in such cases to either draw contents
irrespective of the current matrix, or to track relevant transform state outside of the
canvas.

This method was deprecated
in API level 16.
Hardware accelerated canvases may have any
matrix when passed to a View or Drawable, as it is implementation defined where in the
hierarchy such canvases are created. It is recommended in such cases to either draw contents
irrespective of the current matrix, or to track relevant transform state outside of the
canvas.

Causes the current thread to wait until another thread invokes the
notify() method or the
notifyAll() method for this object, or
some other thread interrupts the current thread, or a certain
amount of real time has elapsed.

CLIP_SAVE_FLAG

CLIP_TO_LAYER_SAVE_FLAG

Clip drawing to the bounds of the offscreen layer, omit at your own peril.

Note: it is strongly recommended to not
omit this flag for any call to saveLayer() and
saveLayerAlpha() variants. Not passing this flag generally
triggers extremely poor performance with hardware accelerated rendering.

MATRIX_SAVE_FLAG

Public constructors

Canvas

Construct an empty raster canvas. Use setBitmap() to specify a bitmap to
draw into. The initial target density is DENSITY_NONE;
this will typically be replaced when a target bitmap is set for the
canvas.

clipRegion

This method was deprecated
in API level 21.
Unlike all other clip calls this API does not respect the
current matrix. Use clipRect(Rect) as an alternative.

Intersect the current clip with the specified region. Note that unlike
clipRect() and clipPath() which transform their arguments by the
current matrix, clipRegion() assumes its argument is already in the
coordinate system of the current layer's bitmap, and so not
transformation is performed.

clipRegion

This method was deprecated
in API level 21.
Unlike all other clip calls this API does not respect the
current matrix. Use clipRect(Rect) as an alternative.

Modify the current clip with the specified region. Note that unlike
clipRect() and clipPath() which transform their arguments by the
current matrix, clipRegion() assumes its argument is already in the
coordinate system of the current layer's bitmap, and so not
transformation is performed.

drawArc

Draw the specified arc, which will be scaled to fit inside the
specified oval.

If the start angle is negative or >= 360, the start angle is treated
as start angle modulo 360.

If the sweep angle is >= 360, then the oval is drawn
completely. Note that this differs slightly from SkPath::arcTo, which
treats the sweep angle modulo 360. If the sweep angle is negative,
the sweep angle is treated as sweep angle modulo 360

The arc is drawn clockwise. An angle of 0 degrees correspond to the
geometric angle of 0 degrees (3 o'clock on a watch.)

Parameters

left

float

top

float

right

float

bottom

float

startAngle

float:
Starting angle (in degrees) where the arc begins

sweepAngle

float:
Sweep angle (in degrees) measured clockwise

useCenter

boolean:
If true, include the center of the oval in the arc, and
close it if it is being stroked. This will draw a wedge

drawArc

Draw the specified arc, which will be scaled to fit inside the
specified oval.

If the start angle is negative or >= 360, the start angle is treated
as start angle modulo 360.

If the sweep angle is >= 360, then the oval is drawn
completely. Note that this differs slightly from SkPath::arcTo, which
treats the sweep angle modulo 360. If the sweep angle is negative,
the sweep angle is treated as sweep angle modulo 360

The arc is drawn clockwise. An angle of 0 degrees correspond to the
geometric angle of 0 degrees (3 o'clock on a watch.)

Parameters

oval

RectF:
The bounds of oval used to define the shape and size
of the arc

startAngle

float:
Starting angle (in degrees) where the arc begins

sweepAngle

float:
Sweep angle (in degrees) measured clockwise

useCenter

boolean:
If true, include the center of the oval in the arc, and
close it if it is being stroked. This will draw a wedge

drawBitmap

This method was deprecated
in API level 21.
Usage with a hardware accelerated canvas
requires an internal copy of color buffer contents every time this method is called. Using a
Bitmap avoids this copy, and allows the application to more explicitly control the lifetime
and copies of pixel data.

Treat the specified array of colors as a bitmap, and draw it. This gives
the same result as first creating a bitmap from the array, and then
drawing it, but this method avoids explicitly creating a bitmap object
which can be more efficient if the colors are changing often.

Parameters

colors

int:
Array of colors representing the pixels of the bitmap

offset

int:
Offset into the array of colors for the first pixel

stride

int:
The number of colors in the array between rows (must be
>= width or <= -width).

x

float:
The X coordinate for where to draw the bitmap

y

float:
The Y coordinate for where to draw the bitmap

width

int:
The width of the bitmap

height

int:
The height of the bitmap

hasAlpha

boolean:
True if the alpha channel of the colors contains valid
values. If false, the alpha byte is ignored (assumed to
be 0xFF for every pixel).

paint

Paint:
May be null. The paint used to draw the bitmap

drawBitmap

This method was deprecated
in API level 21.
Usage with a hardware accelerated canvas
requires an internal copy of color buffer contents every time this method is called. Using a
Bitmap avoids this copy, and allows the application to more explicitly control the lifetime
and copies of pixel data.

Legacy version of drawBitmap(int[] colors, ...) that took ints for x,y

drawBitmap

Draw the specified bitmap, scaling/translating automatically to fill
the destination rectangle. If the source rectangle is not null, it
specifies the subset of the bitmap to draw.

Note: if the paint contains a maskfilter that generates a mask which
extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
Thus the color outside of the original width/height will be the edge
color replicated.

This function ignores the density associated with the bitmap.
This is because the source and destination rectangle coordinate
spaces are in their respective densities, so must already have the
appropriate scaling factor applied.

Parameters

bitmap

Bitmap:
The bitmap to be drawn

src

Rect:
May be null. The subset of the bitmap to be drawn

dst

Rect:
The rectangle that the bitmap will be scaled/translated
to fit into

drawBitmap

Draw the specified bitmap, with its top/left corner at (x,y), using
the specified paint, transformed by the current matrix.

Note: if the paint contains a maskfilter that generates a mask which
extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
Thus the color outside of the original width/height will be the edge
color replicated.

If the bitmap and canvas have different densities, this function
will take care of automatically scaling the bitmap to draw at the
same density as the canvas.

drawBitmap

Draw the specified bitmap, scaling/translating automatically to fill
the destination rectangle. If the source rectangle is not null, it
specifies the subset of the bitmap to draw.

Note: if the paint contains a maskfilter that generates a mask which
extends beyond the bitmap's original width/height (e.g. BlurMaskFilter),
then the bitmap will be drawn as if it were in a Shader with CLAMP mode.
Thus the color outside of the original width/height will be the edge
color replicated.

This function ignores the density associated with the bitmap.
This is because the source and destination rectangle coordinate
spaces are in their respective densities, so must already have the
appropriate scaling factor applied.

Parameters

bitmap

Bitmap:
The bitmap to be drawn

src

Rect:
May be null. The subset of the bitmap to be drawn

dst

RectF:
The rectangle that the bitmap will be scaled/translated
to fit into

paint

Paint:
May be null. The paint used to draw the bitmap

drawBitmapMesh

Draw the bitmap through the mesh, where mesh vertices are evenly
distributed across the bitmap. There are meshWidth+1 vertices across, and
meshHeight+1 vertices down. The verts array is accessed in row-major
order, so that the first meshWidth+1 vertices are distributed across the
top of the bitmap from left to right. A more general version of this
method is drawVertices().

Parameters

bitmap

Bitmap:
The bitmap to draw using the mesh

meshWidth

int:
The number of columns in the mesh. Nothing is drawn if
this is 0

meshHeight

int:
The number of rows in the mesh. Nothing is drawn if
this is 0

verts

float:
Array of x,y pairs, specifying where the mesh should be
drawn. There must be at least
(meshWidth+1) * (meshHeight+1) * 2 + vertOffset values
in the array

vertOffset

int:
Number of verts elements to skip before drawing

colors

int:
May be null. Specifies a color at each vertex, which is
interpolated across the cell, and whose values are
multiplied by the corresponding bitmap colors. If not null,
there must be at least (meshWidth+1) * (meshHeight+1) +
colorOffset values in the array.

drawLines

Draw a series of lines. Each line is taken from 4 consecutive values
in the pts array. Thus to draw 1 line, the array must contain at least 4
values. This is logically the same as drawing the array as follows:
drawLine(pts[0], pts[1], pts[2], pts[3]) followed by
drawLine(pts[4], pts[5], pts[6], pts[7]) and so on.

Parameters

pts

float:
Array of points to draw [x0 y0 x1 y1 x2 y2 ...]

offset

int:
Number of values in the array to skip before drawing.

count

int:
The number of values in the array to process, after
skipping "offset" of them. Since each line uses 4 values,
the number of "lines" that are drawn is really
(count >> 2).

drawPoints

Draw a series of points. Each point is centered at the coordinate
specified by pts[], and its diameter is specified by the paint's stroke
width (as transformed by the canvas' CTM), with special treatment for
a stroke width of 0, which always draws exactly 1 pixel (or at most 4
if antialiasing is enabled). The shape of the point is controlled by
the paint's Cap type. The shape is a square, unless the cap type is
Round, in which case the shape is a circle.

Parameters

pts

float:
Array of points to draw [x0 y0 x1 y1 x2 y2 ...]

offset

int:
Number of values to skip before starting to draw.

count

int:
The number of values to process, after skipping offset
of them. Since one point uses two values, the number of
"points" that are drawn is really (count >> 1).

drawPosText

This method was deprecated
in API level 16.
This method does not support glyph composition and decomposition and
should therefore not be used to render complex scripts. It also doesn't
handle supplementary characters (eg emoji).

Draw the text in the array, with each character's origin specified by
the pos array.

Parameters

text

String:
The text to be drawn

pos

float:
Array of [x,y] positions, used to position each character

paint

Paint:
The paint used for the text (e.g. color, size, style)

drawPosText

This method was deprecated
in API level 16.
This method does not support glyph composition and decomposition and
should therefore not be used to render complex scripts. It also doesn't
handle supplementary characters (eg emoji).

Draw the text in the array, with each character's origin specified by
the pos array.

drawTextRun

Draw a run of text, all in a single direction, with optional context for complex text
shaping.

The run of text includes the characters from start to end in the text. In
addition, the range contextStart to contextEnd is used as context for the
purpose of complex text shaping, such as Arabic text potentially shaped differently based on
the text next to it.

All text outside the range contextStart..contextEnd is ignored. The text between
start and end will be laid out and drawn.

The direction of the run is explicitly specified by isRtl. Thus, this method is
suitable only for runs of a single direction. Alignment of the text is as determined by the
Paint's TextAlign value. Further, 0 <= contextStart <= start <= end <= contextEnd
<= text.length must hold on entry.

Draw the array of vertices, interpreted as triangles (based on mode). The
verts array is required, and specifies the x,y pairs for each vertex. If
texs is non-null, then it is used to specify the coordinate in shader
coordinates to use at each vertex (the paint must have a shader in this
case). If there is no texs array, but there is a color array, then each
color is interpolated across its corresponding triangle in a gradient. If
both texs and colors arrays are present, then they behave as before, but
the resulting color at each pixels is the result of multiplying the
colors from the shader and the color-gradient together. The indices array
is optional, but if it is present, then it is used to specify the index
of each triangle, rather than just walking through the arrays in order.

Parameters

mode

Canvas.VertexMode:
How to interpret the array of vertices

vertexCount

int:
The number of values in the vertices array (and
corresponding texs and colors arrays if non-null). Each logical
vertex is two values (x, y), vertexCount must be a multiple of 2.

verts

float:
Array of vertices for the mesh

vertOffset

int:
Number of values in the verts to skip before drawing.

texs

float:
May be null. If not null, specifies the coordinates to sample
into the current shader (e.g. bitmap tile or gradient)

texOffset

int:
Number of values in texs to skip before drawing.

colors

int:
May be null. If not null, specifies a color for each
vertex, to be interpolated across the triangle.

colorOffset

int:
Number of values in colors to skip before drawing.

indices

short:
If not null, array of indices to reference into the
vertex (texs, colors) array.

indexOffset

int

indexCount

int:
number of entries in the indices array (if not null).

paint

Paint:
Specifies the shader to use if the texs array is non-null.

getClipBounds

Return the bounds of the current clip (in local coordinates) in the
bounds parameter, and return true if it is non-empty. This can be useful
in a way similar to quickReject, in that it tells you that drawing
outside of these bounds will be clipped out.

Parameters

bounds

Rect:
Return the clip bounds here. If it is null, ignore it but
still return true if the current clip is non-empty.

getHeight

getMatrix

This method was deprecated
in API level 16.Hardware accelerated canvases may have any
matrix when passed to a View or Drawable, as it is implementation defined where in the
hierarchy such canvases are created. It is recommended in such cases to either draw contents
irrespective of the current matrix, or to track relevant transform state outside of the
canvas.

Return a new matrix with a copy of the canvas' current transformation
matrix.

getMatrix

This method was deprecated
in API level 16.Hardware accelerated canvases may have any
matrix when passed to a View or Drawable, as it is implementation defined where in the
hierarchy such canvases are created. It is recommended in such cases to either draw contents
irrespective of the current matrix, or to track relevant transform state outside of the
canvas.

Return, in ctm, the current transformation matrix. This does not alter
the matrix in the canvas, but just returns a copy of it.

quickReject

Return true if the specified rectangle, after being transformed by the
current matrix, would lie completely outside of the current clip. Call
this to check if an area you intend to draw into is clipped out (and
therefore you can skip making the draw calls).

Parameters

left

float:
The left side of the rectangle to compare with the
current clip

top

float:
The top of the rectangle to compare with the current
clip

right

float:
The right side of the rectangle to compare with the
current clip

bottom

float:
The bottom of the rectangle to compare with the
current clip

type

Canvas.EdgeType:
AA if the path should be considered antialiased,
since that means it may affect a larger area (more pixels) than
non-antialiased (BW).

Returns

boolean

true if the rect (transformed by the canvas' matrix)
does not intersect with the canvas' clip

quickReject

Return true if the specified path, after being transformed by the
current matrix, would lie completely outside of the current clip. Call
this to check if an area you intend to draw into is clipped out (and
therefore you can skip making the draw calls). Note: for speed it may
return false even if the path itself might not intersect the clip
(i.e. the bounds of the path intersects, but the path does not).

Parameters

path

Path:
The path to compare with the current clip

type

Canvas.EdgeType:
AA if the path should be considered antialiased,
since that means it may affect a larger area (more pixels) than
non-antialiased (BW).

Returns

boolean

true if the path (transformed by the canvas' matrix)
does not intersect with the canvas' clip

quickReject

Return true if the specified rectangle, after being transformed by the
current matrix, would lie completely outside of the current clip. Call
this to check if an area you intend to draw into is clipped out (and
therefore you can skip making the draw calls).

Parameters

rect

RectF:
the rect to compare with the current clip

type

Canvas.EdgeType:
AA if the path should be considered antialiased,
since that means it may affect a larger area (more pixels) than
non-antialiased (BW).

Returns

boolean

true if the rect (transformed by the canvas' matrix)
does not intersect with the canvas' clip

restore

This call balances a previous call to save(), and is used to remove all
modifications to the matrix/clip state since the last save call. It is
an error to call restore() more times than save() was called.

restoreToCount

Efficient way to pop any calls to save() that happened after the save
count reached saveCount. It is an error for saveCount to be less than 1.
Example:
int count = canvas.save();
... // more calls potentially to save()
canvas.restoreToCount(count);
// now the canvas is back in the same state it was before the initial
// call to save().

save

Based on saveFlags, can save the current matrix and clip onto a private
stack.

Note: if possible, use the
parameter-less save(). It is simpler and faster than individually
disabling the saving of matrix or clip with this method.

Subsequent calls to translate,scale,rotate,skew,concat or clipRect,
clipPath will all operate as usual, but when the balancing call to
restore() is made, those calls will be forgotten, and the settings that
existed before the save() will be reinstated.

Parameters

saveFlags

int:
flag bits that specify which parts of the Canvas state
to save/restore

Returns

int

The value to pass to restoreToCount() to balance this save()

save

Subsequent calls to translate,scale,rotate,skew,concat or clipRect,
clipPath will all operate as usual, but when the balancing call to
restore() is made, those calls will be forgotten, and the settings that
existed before the save() will be reinstated.

saveLayer

This behaves the same as save(), but in addition it allocates and
redirects drawing to an offscreen bitmap.

Note: this method is very expensive,
incurring more than double rendering cost for contained content. Avoid
using this method, especially if the bounds provided are large, or if
the CLIP_TO_LAYER_SAVE_FLAG is omitted from the
saveFlags parameter. It is recommended to use a
hardware layer on a View
to apply an xfermode, color filter, or alpha, as it will perform much
better than this method.

All drawing calls are directed to a newly allocated offscreen bitmap.
Only when the balancing call to restore() is made, is that offscreen
buffer drawn back to the current target of the Canvas (either the
screen, it's target Bitmap, or the previous layer).

Attributes of the Paint - alpha,
Xfermode, and
ColorFilter are applied when the
offscreen bitmap is drawn back when restore() is called.

Parameters

bounds

RectF:
May be null. The maximum size the offscreen bitmap
needs to be (in local coordinates)

paint

Paint:
This is copied, and is applied to the offscreen when
restore() is called.

saveLayerAlpha

This behaves the same as save(), but in addition it allocates and
redirects drawing to an offscreen bitmap.

Note: this method is very expensive,
incurring more than double rendering cost for contained content. Avoid
using this method, especially if the bounds provided are large, or if
the CLIP_TO_LAYER_SAVE_FLAG is omitted from the
saveFlags parameter. It is recommended to use a
hardware layer on a View
to apply an xfermode, color filter, or alpha, as it will perform much
better than this method.

All drawing calls are directed to a newly allocated offscreen bitmap.
Only when the balancing call to restore() is made, is that offscreen
buffer drawn back to the current target of the Canvas (either the
screen, it's target Bitmap, or the previous layer).

The alpha parameter is applied when the offscreen bitmap is
drawn back when restore() is called.

Parameters

bounds

RectF:
The maximum size the offscreen bitmap needs to be
(in local coordinates)

alpha

int:
The alpha to apply to the offscreen when it is
drawn during restore()

setBitmap

Specify a bitmap for the canvas to draw into. All canvas state such as
layers, filters, and the save/restore stack are reset with the exception
of the current matrix and clip stack. Additionally, as a side-effect
the canvas' target density is updated to match that of the bitmap.