Community Issues Reference Playground

Experimental SkCanvas ===

Canvas

Canvas provides an interface for drawing, and how the drawing is clipped and transformed. Canvas contains a stack of Matrix and Clip values. Canvas and Paint together provide the state to draw into Surface or Device. Each Canvas draw call transforms the geometry of the object by the concatenation of all Matrix values in the stack. The transformed geometry is clipped by the intersection of all of Clip values in the stack. The Canvas draw calls take Paint parameter for drawing state. Create Paint to supply the drawing state, such as Color, Typeface, Paint Text Size, Paint Stroke Width, Shader and so on. To draw to a pixel-based destination, create Raster Surface or GPU Surface. Request Canvas from Surface to obtain the interface to draw. Canvas generated by Raster Surface draws to memory visible to the CPU. Canvas generated by GPU Surface uses Vulkan or OpenGL to draw to the GPU. Canvas can be constructed to draw to Bitmap without first creating Raster Surface. This approach may be deprecated in the future. To draw to a document, obtain Canvas from SVG Canvas, Document PDF, or Picture Recorder. Document-based Canvas and other Canvas subclasses reference Device describing the destination.

Class SkCanvas

Overview

Subtopics

| topics | description | | --- | --- |

Constants

| constants | description | | --- | --- | | Lattice::Flags | Controls Lattice transparency. | | PointMode | Sets drawPoints options. | | SaveLayerFlags | Sets SaveLayerRec options. | | SrcRectConstraint | Sets drawImageRect options. |

Structs

| struct | description | | --- | --- | | Lattice | Divides Bitmap, Image into a rectangular grid. | | SaveLayerRec | Contains state to create the layer offscreen. |

Constructors

Create the desired type of Surface to obtain its Canvas when possible. Constructors are useful when no Surface is required, and some helpers implicitly create Raster Surface. | | description | | --- | --- | | SkCanvas() | No Surface, no dimensions. | | | No Surface, set dimensions, Surface Properties. | | SkCanvas(SkBaseDevice* device) | Existing Device. (SkBaseDevice is private.) | | SkCanvas(const SkBitmap& bitmap) | Uses existing Bitmap. | | SkCanvas(const SkBitmap& bitmap, const SkSurfaceProps& props) | Uses existing Bitmap and Surface Properties. | | MakeRasterDirect | Creates from SkImageInfo and Pixel Storage. | | MakeRasterDirectN32 | Creates from image data and Pixel Storage. |

Member Functions

| function | description | | --- | --- | | accessTopLayerPixels | Returns writable pixel access if available. | | accessTopRasterHandle | Returns context that tracks Clip and Matrix. | | clear | Fills Clip with Color. | | clipPath | Combines Clip with Path. | | clipRRect | Combines Clip with Round Rect. | | clipRect | Combines Clip with Rect. | | clipRegion | Combines Clip with Region. | | concat | Multiplies Matrix by Matrix. | | discard | Makes Canvas contents undefined. | | drawAnnotation | Associates a Rect with a key-value pair. | | drawArc | Draws Arc using Clip, Matrix, and Paint. | | drawAtlas | Draws sprites using Clip, Matrix, and Paint. | | drawBitmap | Draws Bitmap at (x, y) position. | | drawBitmapLattice | Draws differentially stretched Bitmap. | | drawBitmapNine | Draws Nine Patch Bitmap. | | drawBitmapRect | Draws Bitmap, source Rect to destination Rect. | | drawCircle | Draws Circle using Clip, Matrix, and Paint. | | drawColor | Fills Clip with Color and Blend Mode. | | drawDRRect | Draws double Round Rect stroked or filled. | | drawDrawable | Draws Drawable, encapsulated drawing commands. | | drawIRect | Draws IRect using Clip, Matrix, and Paint. | | drawImage | Draws Image at (x, y) position. | | drawImageLattice | Draws differentially stretched Image. | | drawImageNine | Draws Nine Patch Image. | | drawImageRect | Draws Image, source Rect to destination Rect. | | drawLine | Draws line segment between two points. | | drawOval | Draws Oval using Clip, Matrix, and Paint. | | drawPaint | Fills Clip with Paint. | | drawPatch | Draws cubic Coons patch. | | drawPath | Draws Path using Clip, Matrix, and Paint. | | drawPicture | Draws Picture using Clip and Matrix. | | drawPoint | Draws point at (x, y) position. | | drawPoints | Draws array as points, lines, polygon. | | drawPosText | Draws text at array of (x, y) positions. | | drawPosTextH | Draws text at x positions with common baseline. | | drawRRect | Draws Round Rect using Clip, Matrix, and Paint. | | drawRect | Draws Rect using Clip, Matrix, and Paint. | | drawRegion | Draws Region using Clip, Matrix, and Paint. | | drawRoundRect | Draws Round Rect using Clip, Matrix, and Paint. | | drawText | Draws text at (x, y), using font advance. | | drawTextBlob | Draws text with arrays of positions and Paint. | | drawTextOnPath | Draws text following Path contour. | | drawTextOnPathHV | Draws text following Path with offsets. | | drawTextRSXform | Draws text with array of RSXform. | | drawString | Draws null terminated string at (x, y) using font advance. | | drawVertices | Draws Vertices, a triangle mesh. | | flush | Triggers execution of all pending draw operations. | | getBaseLayerSize | Gets size of base layer in global coordinates. | | getDeviceClipBounds | Returns IRect bounds of Clip. | | getDrawFilter | Legacy; to be deprecated. | | getGrContext | Returns GPU Context of the GPU Surface. | | getLocalClipBounds | Returns Clip bounds in source coordinates. | | getMetaData | Associates additional data with the canvas. | | getProps | Copies Surface Properties if available. | | getSaveCount | Returns depth of stack containing Clip and Matrix. | | getTotalMatrix | Returns Matrix. | | imageInfo | Returns Image Info for Canvas. | | isClipEmpty | Returns if Clip is empty. | | isClipRect | Returns if Clip is Rect and not empty. | | MakeRasterDirect | Creates Canvas from SkImageInfo and pixel data. | | MakeRasterDirectN32 | Creates Canvas from image specifications and pixel data. | | makeSurface | Creates Surface matching SkImageInfo and SkSurfaceProps. | | peekPixels | Returns if Canvas has direct access to its pixels. | | quickReject | Returns if Rect is outside Clip. | | readPixels | Copies and converts rectangle of pixels from Canvas. | | resetMatrix | Resets Matrix to identity. | | restore | Restores changes to Clip and Matrix, pops save stack. | | restoreToCount | Restores changes to Clip and Matrix to given depth. | | rotate | Rotates Matrix. | | save | Saves Clip and Matrix on stack. | | saveLayer | Saves Clip and Matrix on stack; creates offscreen. | | saveLayerAlpha | Saves Clip and Matrix on stack; creates offscreen; sets opacity. | | saveLayerPreserveLCDTextRequests | Saves Clip and Matrix on stack; creates offscreen for LCD text. | | scale | Scales Matrix. | | setAllowSimplifyClip | Experimental. | | setDrawFilter | Legacy; to be deprecated. | | setMatrix | Sets Matrix. | | skew | Skews Matrix. | | translate | Translates Matrix. | | writePixels | Copies and converts rectangle of pixels to Canvas. |

MakeRasterDirect

static std::unique_ptr MakeRasterDirect(const SkImageInfo& info,
                                                  void* pixels, size_t rowBytes)
Allocates raster canvas that will draw directly into pixels. To access pixels after drawing, call flush or peekPixels.

Parameters

info Width, height, Image Color Type, Image Alpha Type, Color Space, of Raster Surface. Width, or height, or both, may be zero.
pixels Pointer to destination pixels buffer. Buffer size should be info height times rowBytes times bytes required for Image Color Type.
rowBytes The interval from one Surface row to the next; equal to or greater than info width times bytes required for Image Color Type.

Return Value

Canvas if all parameters are valid; otherwise, nullptr. Valid parameters include: info dimensions must be zero or positive, and other checks; info must contain Image Color Type and Image Alpha Type supported by Raster Surface; pixels must be not be nullptr; rowBytes must be zero or large enough to contain width pixels of Image Color Type.

Example

Allocates a three by three bitmap, clears it to white, and draws a black pixel in the center.

Example Output

~~~~ --- -x- --- ~~~~

See Also

MakeRasterDirectN32 SkSurface::MakeRasterDirect ---

MakeRasterDirectN32

static std::unique_ptr MakeRasterDirectN32(int width, int height,
                                                     SkPMColor* pixels,
                                                     size_t rowBytes)
Creates Canvas with Raster Surface with inline image specification that draws into pixels. Image Color Type is set to kN32 SkColorType. Image Alpha Type is set to kPremul SkAlphaType. To access pixels after drawing, call flush or peekPixels.

Parameters

width Pixel column count on Raster Surface created. Must be zero or greater.
height Pixel row count on Raster Surface created. Must be zero or greater.
pixels Pointer to destination pixels buffer. Buffer size should be height times rowBytes times four.
rowBytes The interval from one Surface row to the next; equal to or greater than width times four.

Return Value

Canvas if all parameters are valid; otherwise, nullptr. Valid parameters include: width and height must be zero or positive; pixels must be not be nullptr; rowBytes must be zero or large enough to contain width pixels of Image Color Type.

Example

Allocates a three by three bitmap, clears it to white, and draws a black pixel in the center.

Example Output

~~~~ --- -x- --- ~~~~

---

SkCanvas

SkCanvas()
Creates an empty canvas with no backing device/pixels, and zero dimensions.

Return Value

An empty canvas.

Example

Passes a placeholder to a function that requires one.

Example Output

~~~~ paint draws text left to right paint draws text top to bottom paint draws text top to bottom ~~~~

---

SkCanvas

SkCanvas(int width, int height, const SkSurfaceProps* props = NULL)
Creates Canvas of the specified dimensions without a Surface. Used by subclasses with custom implementations for draw methods.

Parameters

width Zero or greater.
height Zero or greater.
props The LCD striping orientation and setting for device independent fonts.

Return Value

Canvas placeholder with dimensions.

Example

Example Output

~~~~ canvas is empty ~~~~

---

SkCanvas

explicit SkCanvas(SkBaseDevice* device)
Construct a canvas that draws into device. Used by child classes of SkCanvas.

Parameters

device Specifies a device for the canvas to draw into.

Return Value

Canvas that can be used to draw into device.

Example

---

SkCanvas

explicit SkCanvas(const SkBitmap& bitmap)
Construct a canvas that draws into bitmap. Sets SkSurfaceProps::kLegacyFontHost InitType in constructed Surface.

Parameters

bitmap Width, height, Image Color Type, Image Alpha Type, and pixel storage of Raster Surface. Bitmap is copied so that subsequently editing bitmap will not affect constructed Canvas.

Return Value

Canvas that can be used to draw into bitmap.

Example

The actual output depends on the installed fonts.

Example Output

~~~~ ----- --x-- --x-- --x-- --x-- --x-- --x-- ----- --x-- --x-- ----- ~~~~

---

Enum SkCanvas::ColorBehavior

enum class ColorBehavior {
kLegacy,
};

Constants

SkCanvas::kLegacy 0

SkCanvas

SkCanvas(const SkBitmap& bitmap, const SkSurfaceProps& props)
Construct a canvas that draws into bitmap. Use props to match the device characteristics, like LCD striping.

Parameters

bitmap Width, height, Image Color Type, Image Alpha Type, and pixel storage of Raster Surface. Bitmap is copied so that subsequently editing bitmap will not affect constructed Canvas.
props The order and orientation of RGB striping; and whether to use device independent fonts.

Return Value

Canvas that can be used to draw into bitmap.

Example

The actual output depends on the installed fonts.

Example Output

~~~~ ----- ---x- ---x- ---x- ---x- ---x- ---x- ----- ---x- ---x- ----- ~~~~

---

~SkCanvas

virtual ~SkCanvas()
Draws State Stack Layer, if any. Free up resources used by Canvas.

Example

---

getMetaData

SkMetaData& getMetaData()
Associates additional data with the canvas. The storage is freed when Canvas is deleted.

Return Value

storage that can be read from and written to.

Example

Example Output

~~~~ before: (null) during: Hello! after: (null) ~~~~

---

imageInfo

SkImageInfo imageInfo() const
Returns Image Info for Canvas. If Canvas is not associated with Raster Surface or GPU Surface, returns SkImageInfo::SkImageInfo() is returned Image Color Type is set to kUnknown SkColorType.

Return Value

dimensions and Image Color Type of Canvas.

Example

---

getProps

bool getProps(SkSurfaceProps* props) const
If Canvas is associated with Raster Surface or GPU Surface, copies Surface Properties and returns true. Otherwise, return false and leave props unchanged.

Parameters

props Pointer to writable SkSurfaceProps.

Return Value

true if Surface Properties was copied.

Example

Example Output

~~~~ isRGB:0 isRGB:1 ~~~~

---

flush

void flush()
Triggers the immediate execution of all pending draw operations. If Canvas is associated with GPU Surface, resolve all pending GPU operations.

Example

---

getBaseLayerSize

virtual SkISize getBaseLayerSize() const
Gets the size of the base or root layer in global canvas coordinates. The origin of the base layer is always (0,0). The current drawable area may be smaller (due to clipping or saveLayer).

Return Value

Integral width and height of base layer.

Example

Example Output

~~~~ clip=10,30 size=20,30 ~~~~

---

makeSurface

sk_sp makeSurface(const SkImageInfo& info,
                             const SkSurfaceProps* props = nullptr)
Creates Surface matching info and props, and associates it with Canvas. If Canvas is already associated with Surface, it cannot create a new Surface.

Parameters

info Initialize Surface with width, height, Image Color Type, Image Alpha Type, and Color Space.
props Use to match if provided, or use the Surface Properties in Canvas otherwise.

Return Value

Surface matching info and props, or nullptr if no match is available.

Example

Example Output

~~~~ compatible != nullptr size = 3, 4 ~~~~

---

getGrContext

virtual GrContext* getGrContext()
Returns GPU Context of the GPU Surface associated with Canvas.

Return Value

GPU Context, if available; nullptr otherwise.

Example

---

accessTopLayerPixels

void* accessTopLayerPixels(SkImageInfo* info, size_t* rowBytes,
                           SkIPoint* origin = NULL)
Returns the pixel base address, Image Info, rowBytes, and origin if the pixels can be read directly. The returned address is only valid while Canvas is in scope and unchanged. Any Canvas call or Surface call may invalidate the returned address and other returned values. If pixels are inaccessible, info, rowBytes, and origin are unchanged.

Parameters

info If not nullptr, copies writable pixels' Image Info.
rowBytes If not nullptr, copies writable pixels' row bytes.
origin If not nullptr, copies Canvas top layer origin, its top left corner.

Return Value

Address of pixels, or nullptr if inaccessible.

Example

Example

Draws "" on the device. Then draws "" in an offscreen layer, and reads the offscreen to add a large dotted "". Finally blends the offscreen with the device. The offscreen and blended result appear on the CPU and GPU but the large dotted "" appear only on the CPU.
---

accessTopRasterHandle

SkRasterHandleAllocator::Handle accessTopRasterHandle() const
Returns custom context that tracks the Matrix and Clip. Use Raster Handle Allocator to blend Skia drawing with custom drawing, typically performed by the host platform's user interface. This accessor returns the custom context created when SkRasterHandleAllocator::MakeCanvas creates a custom canvas with raster storage for the drawing destination.

Return Value

Context of custom allocator.

Example

Example Output

~~~~ context = skia ~~~~

See Also

SkRasterHandleAllocator ---

peekPixels

bool peekPixels(SkPixmap* pixmap)
Returns true if Canvas has direct access to its pixels. Pixels are readable when Device is raster. Pixels are not readable when SkCanvas is returned from GPU Surface, returned by SkDocument::beginPage, returned by SkPictureRecorder::beginRecording, or SkCanvas is the base of a utility class like SkDumpCanvas. pixmap pixel address is only valid while Canvas is in scope and unchanged. Any Canvas or Surface call may invalidate the pixmap values.

Parameters

pixmap storage for Canvas pixel state if Canvas pixels are readable; otherwise, ignored.

Return Value

true if Canvas has direct access to pixels.

Example

Example Output

~~~~ width=256 height=256 ~~~~

---

readPixels

bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
                int srcX, int srcY)
Copies rectangle of pixels from Canvas into dstPixels, converting their Image Color Type and Image Alpha Type. Pixels are readable when Device is raster. Pixels are not readable when SkCanvas is returned from GPU Surface, returned by SkDocument::beginPage, returned by SkPictureRecorder::beginRecording, or SkCanvas is the base of a utility class like SkDumpCanvas. Pixel values are converted only if Canvas Image Color Type and Image Alpha Type does not match dstInfo. Only pixels within the rectangle that intersect Canvas pixels are copied. dstPixels outside the rectangle intersection are unchanged. | source rectangle | value | | --- | --- | | left | srcX | | top | srcY | | width | dstInfo.width() | | height | dstInfo.height() | | canvas pixel bounds | value | | --- | --- | | left | 0 | | top | 0 | | width | imageInfo.width() | | height | imageInfo.height() | Does not copy, and returns false if:
Source rectangle and canvas pixel bounds do not intersect.
Canvas pixels could not be converted to dstInfo Image Color Type or dstInfo Image Alpha Type.
Canvas pixels are not readable; for instance, Canvas is not raster, or is document-based.
dstRowBytes is too small to contain one row of pixels.

Parameters

dstInfo Dimensions, Image Color Type, and Image Alpha Type of dstPixels.
dstPixels Storage for pixels, of size dstInfo.height() times dstRowBytes.
dstRowBytes Size of one destination row, dstInfo.width() times pixel size.
srcX Offset into readable pixels in x.
srcY Offset into readable pixels in y.

Return Value

true if pixels were copied.

Example

Canvas returned by Raster Surface has premultiplied pixel values. clear takes unpremultiplied input with Color Alpha equal 0x80 and Color RGB equal 0x55, 0xAA, 0xFF. Color RGB is multipled by Color Alpha to generate premultipled value 0x802B5580. readPixels converts pixel back to unpremultipled value 0x8056A9FF, introducing error.

Example Output

~~~~ pixel = 802b5580 pixel = 8056a9ff ~~~~

---
bool readPixels(const SkPixmap& pixmap, int srcX, int srcY)
Copies rectangle of pixels from Canvas into Pixmap, converting their Image Color Type and Image Alpha Type. Pixels are readable when Device is raster. Pixels are not readable when SkCanvas is returned from GPU Surface, returned by SkDocument::beginPage, returned by SkPictureRecorder::beginRecording, or SkCanvas is the base of a utility class like SkDumpCanvas. Pixel values are converted only if Canvas Image Color Type and Image Alpha Type does not match bitmap Image Info. Only Pixmap pixels within the rectangle that intersect Canvas pixels are copied. Pixmap pixels outside the rectangle intersection are unchanged. | source rectangle | value | | --- | --- | | left | srcX | | top | srcY | | width | bitmap.width() | | height | bitmap.height() | | canvas pixel bounds | value | | --- | --- | | left | 0 | | top | 0 | | width | imageInfo.width() | | height | imageInfo.height() | Does not copy, and returns false if:
Source rectangle and canvas pixel bounds do not intersect.
Canvas pixels could not be converted to bitmap Image Color Type or bitmap Image Alpha Type.
Canvas pixels are not readable; for instance, Canvas is not raster, or is document-based.
bitmap pixels could not be allocated.
Bitmap Row Bytes is too small to contain one row of pixels.

Parameters

pixmap Receives pixels copied from Canvas.
srcX Offset into readable pixels in x.
srcY Offset into readable pixels in y.

Return Value

true if pixels were copied.

Example

Example Output

~~~~ pixel = 802b5580 ~~~~

---
bool readPixels(const SkBitmap& bitmap, int srcX, int srcY)
Copies pixels enclosed by bitmap offset to (x, y) from Canvas into bitmap, converting their Image Color Type and Image Alpha Type. Pixels are readable when Device is raster. Pixels are not readable when SkCanvas is returned from GPU Surface, returned by SkDocument::beginPage, returned by SkPictureRecorder::beginRecording, or SkCanvas is the base of a utility class like SkDumpCanvas. Allocates pixel storage in bitmap if needed. Pixel values are converted only if Canvas Image Color Type and Image Alpha Type does not match bitmap Image Info. Only pixels within the rectangle that intersect Canvas pixels are copied. Bitamp pixels outside the rectangle intersection are unchanged. | canvas pixel bounds | value | | --- | --- | | left | 0 | | top | 0 | | width | imageInfo.width() | | height | imageInfo.height() | Does not copy, and returns false if:
Bounds formed by (x, y) and bitmap (width, height) and canvas pixel bounds do not intersect.
Canvas pixels could not be converted to bitmap Image Color Type or bitmap Image Alpha Type.
Canvas pixels are not readable; for instance, Canvas is not raster, or is document-based.
bitmap pixels could not be allocated.
Bitmap Row Bytes is too small to contain one row of pixels.

Parameters

bitmap Receives pixels copied from Canvas.
srcX Offset into readable pixels in x.
srcY Offset into readable pixels in y.

Return Value

true if pixels were copied.

Example

Example Output

~~~~ pixel = 802b5580 ~~~~

---

writePixels

bool writePixels(const SkImageInfo& info, const void* pixels, size_t rowBytes,
                 int x, int y)
Copies to Canvas pixels, ignoring the Matrix and Clip, converting to match info Image Color Type and info Image Alpha Type. Pixel values are converted only if Canvas Image Color Type and Image Alpha Type does not match info. Only pixels within the source rectangle that intersect Canvas pixel bounds are copied. Canvas pixels outside the rectangle intersection are unchanged. | source rectangle | value | | --- | --- | | left | x | | top | y | | width | info.width() | | height | info.height() | | canvas pixel bounds | value | | --- | --- | | left | 0 | | top | 0 | | width | imageInfo.width() | | height | imageInfo.height() | Does not copy, and returns false if:
Source rectangle and canvas pixel bounds do not intersect.
pixels could not be converted to Canvas Image Color Type or Canvas Image Alpha Type.
Canvas pixels are not writable; for instance, Canvas is document-based.
rowBytes is too small to contain one row of pixels.

Parameters

info Dimensions, Image Color Type, and Image Alpha Type of pixels.
pixels Pixels to copy, of size info.height() times rowBytes.
rowBytes Offset from one row to the next, usually info.width() times pixel size.
x Offset into Canvas writable pixels in x.
y Offset into Canvas writable pixels in y.

Return Value

true if pixels were written to Canvas.

Example

---
bool writePixels(const SkBitmap& bitmap, int x, int y)
Writes to Canvas pixels, ignoring the Matrix and Clip, converting to match bitmap Image Color Type and bitmap Image Alpha Type. Pixel values are converted only if Canvas Image Color Type and Image Alpha Type does not match bitmap. Only pixels within the source rectangle that intersect Canvas pixel bounds are copied. Canvas pixels outside the rectangle intersection are unchanged. | source rectangle | value | | --- | --- | | left | x | | top | y | | width | bitmap.width() | | height | bitmap.height() | | canvas pixel bounds | value | | --- | --- | | left | 0 | | top | 0 | | width | imageInfo.width() | | height | imageInfo.height() | Does not copy, and returns false if:
Source rectangle and Canvas pixel bounds do not intersect.
bitmap does not have allocated pixels.
bitmap pixels could not be converted to Canvas Image Color Type or Canvas Image Alpha Type.
Canvas pixels are not writable; for instance, Canvas is document-based.
bitmap pixels are inaccessible; for instance, bitmap wraps a texture.

Parameters

bitmap Provides pixels copied to Canvas.
x Offset into Canvas writable pixels in x.
y Offset into Canvas writable pixels in y.

Return Value

true if pixels were written to Canvas.

Example

---

State Stack

Canvas maintains a stack of state that allows hierarchical drawing, commonly used to implement windows and views. The initial state has an identity matrix and and an infinite clip. Even with a wide-open clip, drawing is constrained by the bounds of the Canvas Surface or Device. Canvas savable state consists of Clip, Matrix, and Draw Filter. Clip describes the area that may be drawn to. Matrix transforms the geometry. Draw Filter (deprecated on most platforms) modifies the paint before drawing. save, saveLayer, saveLayerPreserveLCDTextRequests, and saveLayerAlpha save state and return the depth of the stack. restore and restoreToCount revert state to its value when saved. Each state on the stack intersects Clip with the previous Clip, and concatenates Matrix with the previous Matrix. The intersected Clip makes the drawing area the same or smaller; the concatenated Matrix may move the origin and potentially scale or rotate the coordinate space. Canvas does not require balancing the state stack but it is a good idea to do so. Calling save without restore will eventually cause Skia to fail; mismatched save and restore create hard to find bugs. It is not possible to use state to draw outside of the clip defined by the previous state.

Example

Draw to ever smaller clips; then restore drawing to full canvas. Note that the second clipRect is not permitted to enlarge Clip.
Each Clip uses the current Matrix for its coordinates.

Example

While clipRect is given the same rectangle twice, Matrix makes the second clipRect draw at half the size of the first.

See Also

save saveLayer saveLayerPreserveLCDTextRequests saveLayerAlpha restore restoreToCount

save

int save()
Saves Matrix, Clip, and Draw Filter (Draw Filter deprecated on most platforms). Calling restore discards changes to Matrix, Clip, and Draw Filter, restoring the Matrix, Clip, and Draw Filter to their state when save was called. Matrix may be changed by translate, scale, rotate, skew, concat, setMatrix, and resetMatrix. Clip may be changed by clipRect, clipRRect, clipPath, clipRegion. Saved Canvas state is put on a stack; multiple calls to save should be balance by an equal number of calls to restore. Call restoreToCount with result to restore this and subsequent saves.

Return Value

Depth of saved stack.

Example

The black square is translated 50 pixels down and to the right. Restoring Canvas state removes translate from Canvas stack; the red square is not translated, and is drawn at the origin.
---

Layer

Layer allocates a temporary offscreen Bitmap to draw into. When the drawing is complete, the Bitmap is drawn into the Canvas. Layer is saved in a stack along with other saved state. When state with a Layer is restored, the offscreen Bitmap is drawn into the previous layer. Layer may be initialized with the contents of the previous layer. When Layer is restored, its Bitmap can be modified by Paint passed to Layer to apply Color Alpha, Color Filter, Image Filter, and Blend Mode.

saveLayer

int saveLayer(const SkRect* bounds, const SkPaint* paint)
Saves Matrix, Clip, and Draw Filter (Draw Filter deprecated on most platforms), and allocates an offscreen Bitmap for subsequent drawing. Calling restore discards changes to Matrix, Clip, and Draw Filter, and draws the offscreen bitmap. The Matrix, Clip, and Draw Filter are restored to their state when save was called. Matrix may be changed by translate, scale, rotate, skew, concat, setMatrix, and resetMatrix. Clip may be changed by clipRect, clipRRect, clipPath, clipRegion. Rect bounds suggests but does not define the offscreen size. To clip drawing to a specific rectangle, use clipRect. Optional Paint paint applies Color Alpha, Color Filter, Image Filter, and Blend Mode when restore is called. Call restoreToCount with result to restore this and subsequent saves.

Parameters

bounds Used as a hint to limit the size of the offscreen; may be nullptr.
paint Used when restore is called to draw the offscreen; may be nullptr.

Return Value

Depth of saved stack.

Example

Rectangles are blurred by Image Filter when restore draws offscreen to main Canvas.
---
int saveLayer(const SkRect& bounds, const SkPaint* paint)
Saves Matrix, Clip, and Draw Filter (Draw Filter deprecated on most platforms), and allocates an offscreen Bitmap for subsequent drawing. Calling restore discards changes to Matrix, Clip, and Draw Filter, and draws the offscreen Bitmap. The Matrix, Clip, and Draw Filter are restored to their state when save was called. Matrix may be changed by translate, scale, rotate, skew, concat, setMatrix, and resetMatrix. Clip may be changed by clipRect, clipRRect, clipPath, clipRegion. bounds suggests but does not define the offscreen size. To clip drawing to a specific rectangle, use clipRect. Optional Paint paint applies Color Alpha, Color Filter, Image Filter, and Blend Mode when restore is called. Call restoreToCount with result to restore this and subsequent saves.

Parameters

bounds Used as a hint to limit the size of the offscreen; may be nullptr.
paint Used when restore is called to draw the offscreen; may be nullptr.

Return Value

Depth of saved stack.

Example

Rectangles are blurred by Image Filter when restore draws offscreen to main Canvas. The red rectangle is clipped; it does not fully fit on the offscreen Canvas. Image Filter blurs past edge of offscreen so red rectangle is blurred on all sides.
---

saveLayerPreserveLCDTextRequests

int saveLayerPreserveLCDTextRequests(const SkRect* bounds, const SkPaint* paint)
Saves Matrix, Clip, and Draw Filter (Draw Filter deprecated on most platforms), and allocates an offscreen bitmap for subsequent drawing. LCD Text is preserved when the offscreen is drawn to the prior layer. Draw text on an opaque background so that LCD Text blends correctly with the prior layer. Calling restore discards changes to Matrix, Clip, and Draw Filter, and draws the offscreen bitmap. The Matrix, Clip, and Draw Filter are restored to their state when save was called. Matrix may be changed by translate, scale, rotate, skew, concat, setMatrix, and resetMatrix. Clip may be changed by clipRect, clipRRect, clipPath, clipRegion. Draw LCD Text on an opaque background to get good results. bounds suggests but does not define the offscreen size. To clip drawing to a specific rectangle, use clipRect. paint modifies how the offscreen overlays the prior layer. Color Alpha, Blend Mode, Color Filter, Draw Looper, Image Filter, and Mask Filter, affect the offscreen draw. Call restoreToCount with result to restore this and subsequent saves.

Parameters

bounds Used as a hint to limit the size of the offscreen; may be nullptr.
paint Used when restore is called to draw the offscreen; may be nullptr.

Return Value

Depth of saved stack.

Example

---

saveLayerAlpha

int saveLayerAlpha(const SkRect* bounds, U8CPU alpha)
Saves Matrix, Clip, and Draw Filter (Draw Filter deprecated on most platforms), and allocates an offscreen bitmap for subsequent drawing. Calling restore discards changes to Matrix, Clip, and Draw Filter, and blends the offscreen bitmap with alpha opacity onto the prior layer. The Matrix, Clip, and Draw Filter are restored to their state when save was called. Matrix may be changed by translate, scale, rotate, skew, concat, setMatrix, and resetMatrix. Clip may be changed by clipRect, clipRRect, clipPath, clipRegion. bounds suggests but does not define the offscreen size. To clip drawing to a specific rectangle, use clipRect. Call restoreToCount with result to restore this and subsequent saves.

Parameters

bounds Used as a hint to limit the size of the offscreen; may be nullptr.
alpha The opacity of the offscreen; zero is fully transparent, 255 is fully opaque.

Return Value

Depth of saved stack.

Example

---

Enum SkCanvas::SaveLayerFlags

enum {
kIsOpaque SaveLayerFlag = 1 << 0,
kPreserveLCDText SaveLayerFlag = 1 << 1,
kInitWithPrevious SaveLayerFlag = 1 << 2,
};

typedef uint32_t SaveLayerFlags;
SaveLayerFlags provides options that may be used in any combination in SaveLayerRec, defining how the offscreen allocated by saveLayer operates.

Constants

SkCanvas::kIsOpaque_SaveLayerFlag 1Creates offscreen without transparency. Flag is ignored if layer Paint contains Image Filter or Color Filter.
SkCanvas::kPreserveLCDText_SaveLayerFlag 2Creates offscreen for LCD text. Flag is ignored if layer Paint contains Image Filter or Color Filter.
SkCanvas::kInitWithPrevious_SaveLayerFlag 4Initializes offscreen with the contents of the previous layer.

Example

Canvas layer captures red and blue circles scaled up by four. scalePaint blends offscreen back with transparency.

Struct SkCanvas::SaveLayerRec

struct SaveLayerRec {
SaveLayerRec(...

const SkRect           fBounds;
const SkPaint*          fPaint;
const SkImageFilter*    fBackdrop;
SaveLayerFlags          fSaveLayerFlags;
};
SaveLayerRec contains the state used to create the layer offscreen. const SkRect* fBounds fBounds is used as a hint to limit the size of the offscreen; may be nullptr. fBounds suggests but does not define the offscreen size. To clip drawing to a specific rectangle, use clipRect. const SkPaint* fPaint fPaint modifies how the offscreen overlays the prior layer; may be nullptr. Color Alpha, Blend Mode, Color Filter, Draw Looper, Image Filter, and Mask Filter affect the offscreen draw. const SkImageFilter* fBackdrop fBackdrop applies Image Filter to the prior layer when copying to the layer offscreen; may be nullptr. Use kInitWithPrevious SaveLayerFlag to copy the prior layer without a Image Filter. const SkImage* fClipMask may be nullptr. const SkMatrix* fClipMatrix may be nullptr. SaveLayerFlags fSaveLayerFlags fSaveLayerFlags are used to create layer offscreen without transparency, create layer offscreen for LCD text, and to create layer offscreen with the contents of the previous layer.

Example

Canvas layer captures a red anti-aliased circle and a blue aliased circle scaled up by four. After drawing another unscaled red circle on top, the offscreen is transferred to the main canvas.

SaveLayerRec

SaveLayerRec()
Sets fBounds, fPaint, and fBackdrop to nullptr. Clears fSaveLayerFlags.

Return Value

empty SaveLayerRec.

Example

Example Output

~~~~ rec1 == rec2 ~~~~

---
SaveLayerRec(const SkRect* bounds, const SkPaint* paint,
             SaveLayerFlags saveLayerFlags = 0)
Sets fBounds, fPaint, and fSaveLayerFlags; sets fBackdrop to nullptr.

Parameters

bounds Offscreen dimensions; may be nullptr.
paint Applied to offscreen when overlaying prior layer; may be nullptr.
saveLayerFlags SaveLayerRec options to modify offscreen.

Return Value

SaveLayerRec with empty backdrop.

Example

Example Output

~~~~ rec1 == rec2 ~~~~

---
SaveLayerRec(const SkRect* bounds, const SkPaint* paint,
             const SkImageFilter* backdrop, SaveLayerFlags saveLayerFlags)
Sets fBounds, fPaint, fBackdrop, and fSaveLayerFlags.

Parameters

bounds Offscreen dimensions; may be nullptr.
paint Applied to offscreen when overlaying prior layer; may be nullptr.
backdrop Copies prior layer to offscreen with Image Filter; may be nullptr.
saveLayerFlags SaveLayerRec options to modify offscreen.

Return Value

SaveLayerRec fully specified.

Example

Example Output

~~~~ rec1 == rec2 ~~~~

---
SaveLayerRec(const SkRect* bounds, const SkPaint* paint,
             const SkImageFilter* backdrop, const SkImage* clipMask,
             const SkMatrix* clipMatrix, SaveLayerFlags saveLayerFlags)
Not ready for general use.

Parameters

bounds Offscreen dimensions; may be nullptr.
paint Applied to offscreen when overlaying prior layer; may be nullptr.
backdrop Copies prior layer to offscreen with Image Filter; may be nullptr.
clipMask May be nullptr.
clipMatrix May be nullptr.
saveLayerFlags SaveLayerRec options to modify offscreen.

Return Value

SaveLayerRec fully specified. ---

int saveLayer(const SaveLayerRec& layerRec)
Saves Matrix, Clip, and Draw Filter (Draw Filter deprecated on most platforms), and allocates an offscreen bitmap for subsequent drawing. Calling restore discards changes to Matrix, Clip, and Draw Filter, and blends the offscreen bitmap with alpha opacity onto the prior layer. The Matrix, Clip, and Draw Filter are restored to their state when save was called. Matrix may be changed by translate, scale, rotate, skew, concat, setMatrix, and resetMatrix. Clip may be changed by clipRect, clipRRect, clipPath, clipRegion. SaveLayerRec contains the state used to create the layer offscreen. Call restoreToCount with result to restore this and subsequent saves.

Parameters

layerRec offscreen state.

Return Value

depth of save state stack.

Example

The example draws an image, and saves it into a layer with kInitWithPrevious SaveLayerFlag. Next it punches a hole in the layer and restore with SkBlendMode::kPlus. Where the layer was cleared, the original image will draw unchanged. Outside of the circle the mandrill is brightened.
---

restore

void restore()
Removes changes to Matrix, Clip, and Draw Filter since Canvas state was last saved. The state is removed from the stack. Does nothing if the stack is empty.

Example

---

getSaveCount

int getSaveCount() const
Returns the number of saved states, each containing: Matrix, Clip, and Draw Filter. Equals the number of save calls less the number of restore calls plus one. The save count of a new canvas is one.

Return Value

depth of save state stack.

Example

Example Output

~~~~ depth = 1 depth = 2 depth = 1 ~~~~

---

restoreToCount

void restoreToCount(int saveCount)
Restores state to Matrix, Clip, and Draw Filter values when save, saveLayer, saveLayerPreserveLCDTextRequests, or saveLayerAlpha returned saveCount. Does nothing if saveCount is greater than state stack count. Restores state to initial values if saveCount is less than or equal to one.

Parameters

saveCount The depth of state stack to restore.

Example

Example Output

~~~~ depth = 1 depth = 3 depth = 1 ~~~~

---

Matrix

translate

void translate(SkScalar dx, SkScalar dy)
Translate Matrix by dx along the x-axis and dy along the y-axis. Mathematically, replace Matrix with a translation matrix pre-multiplied with Matrix. This has the effect of moving the drawing by (dx, dy) before transforming the result with Matrix.

Parameters

dx The distance to translate in x.
dy The distance to translate in y.

Example

scale followed by translate produces different results from translate followed by scale. The blue stroke follows translate of (50, 50); a black fill follows scale of (2, 1/2.f). After restoring the clip, which resets Matrix, a red frame follows the same scale of (2, 1/2.f); a gray fill follows translate of (50, 50).
---

scale

void scale(SkScalar sx, SkScalar sy)
Scale Matrix by sx on the x-axis and sy on the y-axis. Mathematically, replace Matrix with a scale matrix pre-multiplied with Matrix. This has the effect of scaling the drawing by (sx, sy) before transforming the result with Matrix.

Parameters

sx The amount to scale in x.
sy The amount to scale in y.

Example

---

rotate

void rotate(SkScalar degrees)
Rotate Matrix by degrees. Positive degrees rotates clockwise. Mathematically, replace Matrix with a rotation matrix pre-multiplied with Matrix. This has the effect of rotating the drawing by degrees before transforming the result with Matrix.

Parameters

degrees The amount to rotate, in degrees.

Example

Draw clock hands at time 5:10. The hour hand and minute hand point up and are rotated clockwise.
---
void rotate(SkScalar degrees, SkScalar px, SkScalar py)
Rotate Matrix by degrees about a point at (px, py). Positive degrees rotates clockwise. Mathematically, construct a rotation matrix. Pre-multiply the rotation matrix by a translation matrix, then replace Matrix with the resulting matrix pre-multiplied with Matrix. This has the effect of rotating the drawing about a given point before transforming the result with Matrix.

Parameters

degrees The amount to rotate, in degrees.
px The x coordinate of the point to rotate about.
py The y coordinate of the point to rotate about.

Example

---

skew

void skew(SkScalar sx, SkScalar sy)
Skew Matrix by sx on the x-axis and sy on the y-axis. A positive value of sx skews the drawing right as y increases; a positive value of sy skews the drawing down as x increases. Mathematically, replace Matrix with a skew matrix pre-multiplied with Matrix. Preconcat the current matrix with the specified skew.

Parameters

This has the effect of scaling the drawing by (sx, sy) before transforming the result with Matrix.
sx The amount to skew in x.
sy The amount to skew in y.

Example

Black text mimics an oblique text style by using a negative skew in x that shifts the geometry to the right as the y values decrease. Red text uses a positive skew in y to shift the geometry down as the x values increase. Blue text combines x and y skew to rotate and scale.
---

concat

void concat(const SkMatrix& matrix)
Replace Matrix with matrix pre-multiplied with Matrix. This has the effect of transforming the drawn geometry by matrix, before transforming the result with Matrix.

Parameters

matrix Pre-multiply with Matrix.

Example

---

setMatrix

void setMatrix(const SkMatrix& matrix)
Replace Matrix with matrix. Unlike concat, any prior matrix state is overwritten.

Parameters

matrix Copied into Matrix.

Example

---

resetMatrix

void resetMatrix()
Sets Matrix to the identity matrix. Any prior matrix state is overwritten.

Example

---

getTotalMatrix

const SkMatrix& getTotalMatrix() const
Returns Matrix. This does not account for translation by Device or Surface.

Return Value

Matrix on Canvas.

Example

Example Output

~~~~ isIdentity true ~~~~

---

Clip

Clip is built from a stack of clipping paths. Each Path in the stack can be constructed from one or more Path Contour elements. The Path Contour may be composed of any number of Path Verb segments. Each Path Contour forms a closed area; Path Fill Type defines the area enclosed by Path Contour. Clip stack of Path elements successfully restrict the Path area. Each Path is transformed by Matrix, then intersected with or subtracted from the prior Clip to form the replacement Clip. Use SkClipOp::kDifference to subtract Path from Clip; use SkClipOp::kIntersect to intersect Path with Clip. A clipping Path may be anti-aliased; if Path, after transformation, is composed of horizontal and vertical lines, clearing Anti-alias allows whole pixels to either be inside or outside the clip. The fastest drawing has a aliased, rectanglar clip. If clipping Path has Anti-alias set, clip may partially clip a pixel, requiring that drawing blend partially with the destination along the edge. A rotated rectangular anti-aliased clip looks smoother but draws slower. Clip can combine with Rect and Round Rect primitives; like Path, these are transformed by Matrix before they are combined with Clip. Clip can combine with Region. Region is assumed to be in Device coordinates and is unaffected by Matrix.

Example

Draw a red circle with an aliased clip and an anti-aliased clip. Use an image filter to zoom into the pixels drawn. The edge of the aliased clip fully draws pixels in the red circle. The edge of the anti-aliased clip partially draws pixels in the red circle.

clipRect

void clipRect(const SkRect& rect, SkClipOp op, bool doAntiAlias)
Replace Clip with the intersection or difference of Clip and rect, with an aliased or anti-aliased clip edge. rect is transformed by Matrix before it is combined with Clip.

Parameters

rect Rectangle to combine with Clip.
op Clip Op to apply to Clip.
doAntiAlias true if Clip is to be anti-aliased.

Example

---
void clipRect(const SkRect& rect, SkClipOp op)
Replace Clip with the intersection or difference of Clip and rect. Resulting Clip is aliased; pixels are fully contained by the clip. rect is transformed by Matrix before it is combined with Clip.

Parameters

rect Rectangle to combine with Clip.
op Clip Op to apply to Clip.

Example

---
void clipRect(const SkRect& rect, bool doAntiAlias = false)
Replace Clip with the intersection of Clip and rect. Resulting Clip is aliased; pixels are fully contained by the clip. rect is transformed by Matrix before it is combined with Clip.

Parameters

rect Rectangle to combine with Clip.
doAntiAlias true if Clip is to be anti-aliased.

Example

A circle drawn in pieces looks uniform when drawn aliased. The same circle pieces blend with pixels more than once when anti-aliased, visible as a thin pair of lines through the right circle.
---

androidFramework_setDeviceClipRestriction

void androidFramework_setDeviceClipRestriction(const SkIRect& rect)
Sets the max clip rectangle, which can be set by clipRect, clipRRect and clipPath and intersect the current clip with the specified rect. The max clip affects only future ops (it is not retroactive). The clip restriction is not recorded in pictures.

Parameters

---
rect The maximum allowed clip in device coordinates.

clipRRect

void clipRRect(const SkRRect& rrect, SkClipOp op, bool doAntiAlias)
Replace Clip with the intersection or difference of Clip and rrect, with an aliased or anti-aliased clip edge. rrect is transformed by Matrix before it is combined with Clip.

Parameters

rrect Round Rect to combine with Clip.
op Clip Op to apply to Clip.
doAntiAlias true if Clip is to be antialiased.

Example

---
void clipRRect(const SkRRect& rrect, SkClipOp op)
Replace Clip with the intersection or difference of Clip and rrect. Resulting Clip is aliased; pixels are fully contained by the clip. rrect is transformed by Matrix before it is combined with Clip.

Parameters

rrect Round Rect to combine with Clip.
op Clip Op to apply to Clip.

Example

---
void clipRRect(const SkRRect& rrect, bool doAntiAlias = false)
Replace Clip with the intersection of Clip and rrect, with an aliased or anti-aliased clip edge. rrect is transformed by Matrix before it is combined with Clip.

Parameters

rrect Round Rect to combine with Clip.
doAntiAlias true if Clip is to be antialiased.

Example

---

clipPath

void clipPath(const SkPath& path, SkClipOp op, bool doAntiAlias)
Replace Clip with the intersection or difference of Clip and path, with an aliased or anti-aliased clip edge. Path Fill Type determines if path describes the area inside or outside its contours; and if Path Contour overlaps itself or another Path Contour, whether the overlaps form part of the area. path is transformed by Matrix before it is combined with Clip.

Parameters

path Path to combine with Clip.
op Clip Op to apply to Clip.
doAntiAlias true if Clip is to be antialiased.

Example

Top figure uses SkPath::kInverseWinding FillType and SkClipOp::kDifference; area outside clip is subtracted from circle. Bottom figure uses SkPath::kWinding FillType and SkClipOp::kIntersect; area inside clip is intersected with circle.
---
void clipPath(const SkPath& path, SkClipOp op)
Replace Clip with the intersection or difference of Clip and path. Resulting Clip is aliased; pixels are fully contained by the clip. Path Fill Type determines if path describes the area inside or outside its contours; and if Path Contour overlaps itself or another Path Contour, whether the overlaps form part of the area. path is transformed by Matrix before it is combined with Clip.

Parameters

path Path to combine with Clip.
op Clip Op to apply to Clip.

Example

Overlapping Rects form a clip. When clip's Path Fill Type is set to SkPath::kWinding FillType, the overlap is included. Set to SkPath::kEvenOdd FillType, the overlap is excluded and forms a hole.
---
void clipPath(const SkPath& path, bool doAntiAlias = false)
Replace Clip with the intersection of Clip and path. Resulting Clip is aliased; pixels are fully contained by the clip. Path Fill Type determines if path describes the area inside or outside its contours; and if Path Contour overlaps itself or another Path Contour, whether the overlaps form part of the area. path is transformed by Matrix before it is combined with Clip.

Parameters

path Path to combine with Clip.
doAntiAlias true if Clip is to be antialiased.

Example

Clip loops over itself covering its center twice. When clip's Path Fill Type is set to SkPath::kWinding FillType, the overlap is included. Set to SkPath::kEvenOdd FillType, the overlap is excluded and forms a hole.
---

setAllowSimplifyClip

void setAllowSimplifyClip(bool allow)
Only used for testing.Set to simplify clip stack using path ops. ---

clipRegion

void clipRegion(const SkRegion& deviceRgn, SkClipOp op = SkClipOp::kIntersect)
Replace Clip with the intersection or difference of Clip and Region deviceRgn. Resulting Clip is aliased; pixels are fully contained by the clip. deviceRgn is unaffected by Matrix.

Parameters

deviceRgn Region to combine with Clip.
op Clip Op to apply to Clip.

Example

region is unaffected by canvas rotation; rect is affected by canvas rotation. Both clips are aliased; this is unnoticable on Region clip because it aligns to pixel boundaries.
---

quickReject

bool quickReject(const SkRect& rect) const
Return true if Rect rect, transformed by Matrix, can be quickly determined to be outside of Clip. May return false even though rect is outside of Clip. Use to check if an area to be drawn is clipped out, to skip subsequent draw calls.

Parameters

rect Rect to compare with Clip.

Return Value

true if rect, transformed by Matrix, does not intersect Clip.

Example

Example Output

~~~~ quickReject true quickReject false ~~~~

---
bool quickReject(const SkPath& path) const
Return true if path, transformed by Matrix, can be quickly determined to be outside of Clip. May return false even though path is outside of Clip. Use to check if an area to be drawn is clipped out, to skip subsequent draw calls.

Parameters

path Path to compare with Clip.

Return Value

true if path, transformed by Matrix, does not intersect Clip.

Example

Example Output

~~~~ quickReject true quickReject false ~~~~

---

getLocalClipBounds

SkRect getLocalClipBounds() const
Return bounds of Clip, transformed by inverse of Matrix. If Clip is empty, return SkRect::MakeEmpty, where all Rect sides equal zero. Rect returned is outset by one to account for partial pixel coverage if Clip is anti-aliased.

Return Value

bounds of Clip in local coordinates.

Example

Initial bounds is device bounds outset by 1 on all sides. Clipped bounds is clipPath bounds outset by 1 on all sides. Scaling the canvas by two in x and y scales the local bounds by 1/2 in x and y.

Example Output

~~~~ left:-1 top:-1 right:257 bottom:257 left:29 top:129 right:121 bottom:231 left:14.5 top:64.5 right:60.5 bottom:115.5 ~~~~

---
bool getLocalClipBounds(SkRect* bounds) const
Return bounds of Clip, transformed by inverse of Matrix. If Clip is empty, return false, and set bounds to SkRect::MakeEmpty, where all Rect sides equal zero. bounds is outset by one to account for partial pixel coverage if Clip is anti-aliased.

Parameters

bounds Rect of Clip in local coordinates.

Return Value

true if Clip bounds is not empty.

Example

Example Output

~~~~ local bounds empty = false local bounds empty = true ~~~~

---

getDeviceClipBounds

SkIRect getDeviceClipBounds() const
Return IRect bounds of Clip, unaffected by Matrix. If Clip is empty, return SkRect::MakeEmpty, where all Rect sides equal zero. Unlike getLocalClipBounds, returned IRect is not outset.

Return Value

bounds of Clip in Device coordinates.

Example

Initial bounds is device bounds, not outset. Clipped bounds is clipPath bounds, not outset. Scaling the canvas by 1/2 in x and y scales the device bounds by 1/2 in x and y.

Example Output

~~~~ left:0 top:0 right:256 bottom:256 left:30 top:130 right:120 bottom:230 left:15 top:65 right:60 bottom:115 ~~~~

---
bool getDeviceClipBounds(SkIRect* bounds) const
Return IRect bounds of Clip, unaffected by Matrix. If Clip is empty, return false, and set bounds to SkRect::MakeEmpty, where all Rect sides equal zero. Unlike getLocalClipBounds, bounds is not outset.

Parameters

bounds Rect of Clip in device coordinates.

Return Value

true if Clip bounds is not empty.

Example

Example Output

~~~~ device bounds empty = false device bounds empty = true ~~~~

---

drawColor

void drawColor(SkColor color, SkBlendMode mode = SkBlendMode::kSrcOver)
Fill Clip with Color color. mode determines how Color ARGB is combined with destination.

Parameters

color Unpremultiplied Color ARGB.
mode SkBlendMode used to combine source color and destination.

Example

---

clear

void clear(SkColor color)
Fill Clip with Color color using SkBlendMode::kSrc. This has the effect of replacing all pixels contained by Clip with color.

Parameters

color Unpremultiplied Color ARGB.

Example

---

discard

void discard()
Make Canvas contents undefined. Subsequent calls that read Canvas pixels, such as drawing with SkBlendMode, return undefined results. discard does not change Clip or Matrix. discard may do nothing, depending on the implementation of Surface or Device that created Canvas. discard allows optimized performance on subsequent draws by removing cached data associated with Surface or Device. It is not necessary to call discard once done with Canvas; any cached data is deleted when owning Surface or Device is deleted. ---

drawPaint

void drawPaint(const SkPaint& paint)
Fill Clip with Paint paint. drawPaint is affected by Paint components Rasterizer, Mask Filter, Shader, Color Filter, Image Filter, and Blend Mode; but not by Path Effect.

Parameters

paint Used to fill the canvas.

Example

---

Enum SkCanvas::PointMode

enum PointMode {
kPoints PointMode,
kLines PointMode,
kPolygon PointMode 
};
Selects if an array of points are drawn as discrete points, as lines, or as an open polygon.

Constants

SkCanvas::kPoints_PointMode 0Draw each point separately.
SkCanvas::kLines_PointMode 1Draw each pair of points as a line segment.
SkCanvas::kPolygon_PointMode 2Draw the array of points as a open polygon.

Example

The upper left corner shows three squares when drawn as points. The upper right corner shows one line; when drawn as lines, two points are required per line. The lower right corner shows two lines; when draw as polygon, no miter is drawn at the corner. The lower left corner shows two lines with a miter when path contains polygon.

drawPoints

void drawPoints(PointMode mode, size_t count, const SkPoint pts[],
                const SkPaint& paint)
Draw pts using Clip, Matrix and Paint paint. count is the number of points; if count is less than one, drawPoints has no effect. mode may be one of: kPoints PointMode, kLines PointMode, or kPolygon PointMode. If mode is kPoints PointMode, the shape of point drawn depends on paint Paint Stroke Cap. If paint is set to SkPaint::kRound Cap, each point draws a circle of diameter Paint Stroke Width. If paint is set to SkPaint::kSquare Cap or SkPaint::kButt Cap, each point draws a square of width and height Paint Stroke Width. If mode is kLines PointMode, each pair of points draws a line segment. One line is drawn for every two points; each point is used once. If count is odd, the final point is ignored. If mode is kPolygon PointMode, each adjacent pair of points draws a line segment. count minus one lines are drawn; the first and last point are used once. Each line segment respects paint Paint Stroke Cap and Paint Stroke Width. Paint Style is ignored, as if were set to SkPaint::kStroke Style. drawPoints always draws each element one at a time; drawPoints is not affected by Paint Stroke Join, and unlike drawPath, does not create a mask from all points and lines before drawing.

Parameters

mode Whether pts draws points or lines.
count The number of points in the array.
pts Array of points to draw.
paint Stroke, blend, color, and so on, used to draw.

Example

The first column draws points.
The second column draws points as lines.
The third column draws points as a polygon.
The fourth column draws points as a polygonal path.
The first row uses a round cap and round join.
The second row uses a square cap and a miter join.
The third row uses a butt cap and a bevel join.
The transparent color makes multiple line draws visible; the path is drawn all at once.
---

drawPoint

void drawPoint(SkScalar x, SkScalar y, const SkPaint& paint)
Draw point at (x, y) using Clip, Matrix and Paint paint. The shape of point drawn depends on paint Paint Stroke Cap. If paint is set to SkPaint::kRound Cap, draw a circle of diameter Paint Stroke Width. If paint is set to SkPaint::kSquare Cap or SkPaint::kButt Cap, draw a square of width and height Paint Stroke Width. Paint Style is ignored, as if were set to SkPaint::kStroke Style.

Parameters

x Left edge of circle or square.
y Top edge of circle or square.
paint Stroke, blend, color, and so on, used to draw.

Example

---

drawLine

void drawLine(SkScalar x0, SkScalar y0, SkScalar x1, SkScalar y1,
              const SkPaint& paint)
Draw line segment from (x0, y0) to (x1, y1) using Clip, Matrix, and Paint paint. In paint: Paint Stroke Width describes the line thickness; Paint Stroke Cap draws the end rounded or square; Paint Style is ignored, as if were set to SkPaint::kStroke Style.

Parameters

x0 Start of line segment on x-axis.
y0 Start of line segment on y-axis.
x1 End of line segment on x-axis.
y1 End of line segment on y-axis.
paint Stroke, blend, color, and so on, used to draw.

Example

---

drawRect

void drawRect(const SkRect& rect, const SkPaint& paint)
Draw Rect rect using Clip, Matrix, and Paint paint. In paint: Paint Style determines if rectangle is stroked or filled; if stroked, Paint Stroke Width describes the line thickness, and Paint Stroke Join draws the corners rounded or square.

Parameters

rect The rectangle to be drawn.
paint Stroke or fill, blend, color, and so on, used to draw.

Example

---

drawIRect

void drawIRect(const SkIRect& rect, const SkPaint& paint)
Draw IRect rect using Clip, Matrix, and Paint paint. In paint: Paint Style determines if rectangle is stroked or filled; if stroked, Paint Stroke Width describes the line thickness, and Paint Stroke Join draws the corners rounded or square.

Parameters

rect The rectangle to be drawn.
paint Stroke or fill, blend, color, and so on, used to draw.

Example

---

drawRegion

void drawRegion(const SkRegion& region, const SkPaint& paint)
Draw Region region using Clip, Matrix, and Paint paint. In paint: Paint Style determines if rectangle is stroked or filled; if stroked, Paint Stroke Width describes the line thickness, and Paint Stroke Join draws the corners rounded or square.

Parameters

region The region to be drawn.
paint Paint stroke or fill, blend, color, and so on, used to draw.

Example

---

drawOval

void drawOval(const SkRect& oval, const SkPaint& paint)
Draw Oval oval using Clip, Matrix, and Paint. In paint: Paint Style determines if Oval is stroked or filled; if stroked, Paint Stroke Width describes the line thickness.

Parameters

oval Rect bounds of Oval.
paint Paint stroke or fill, blend, color, and so on, used to draw.

Example

---

drawRRect

void drawRRect(const SkRRect& rrect, const SkPaint& paint)
Draw Round Rect rrect using Clip, Matrix, and Paint paint. In paint: Paint Style determines if rrect is stroked or filled; if stroked, Paint Stroke Width describes the line thickness. rrect may represent a rectangle, circle, oval, uniformly rounded rectangle, or may have any combination of positive non-square radii for the four corners.

Parameters

rrect Round Rect with up to eight corner radii to draw.
paint Paint stroke or fill, blend, color, and so on, used to draw.

Example

---

drawDRRect

void drawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint)
Draw Round Rect outer and inner using Clip, Matrix, and Paint paint. outer must contain inner or the drawing is undefined. In paint: Paint Style determines if rrect is stroked or filled; if stroked, Paint Stroke Width describes the line thickness. If stroked and Round Rect corner has zero length radii, Paint Stroke Join can draw corners rounded or square. GPU-backed platforms take advantage of drawDRRect since both outer and inner are concave and outer contains inner. These platforms may not be able to draw Path built with identical data as fast.

Parameters

outer Round Rect outer bounds to draw.
inner Round Rect inner bounds to draw.
paint Paint stroke or fill, blend, color, and so on, used to draw.

Example

Example

Outer Rect has no corner radii, but stroke join is rounded. Inner Round Rect has corner radii; outset stroke increases radii of corners. Stroke join does not affect inner Round Rect since it has no sharp corners.
---

drawCircle

void drawCircle(SkScalar cx, SkScalar cy, SkScalar radius, const SkPaint& paint)
Draw Circle at (cx, cy) with radius using Clip, Matrix, and Paint paint. If radius is zero or less, nothing is drawn. In paint: Paint Style determines if Circle is stroked or filled; if stroked, Paint Stroke Width describes the line thickness.

Parameters

cx Circle center on the x-axis.
cy Circle center on the y-axis.
radius Half the diameter of Circle.
paint Paint stroke or fill, blend, color, and so on, used to draw.

Example

---

drawArc

void drawArc(const SkRect& oval, SkScalar startAngle, SkScalar sweepAngle,
             bool useCenter, const SkPaint& paint)
Draw Arc using Clip, Matrix, and Paint paint. Arc is part of Oval bounded by oval, sweeping from startAngle to startAngle plus sweepAngle. startAngle and sweepAngle are in degrees. startAngle of zero places start point at the right middle edge of oval. A positive sweepAngle places Arc end point clockwise from start point; a negative sweepAngle places Arc end point counterclockwise from start point. sweepAngle may exceed 360 degrees, a full circle. If useCenter is true, draw a wedge that includes lines from oval center to Arc end points. If useCenter is false, draw Arc between end points. If Rect oval is empty or sweepAngle is zero, nothing is drawn.

Parameters

oval Rect bounds of Oval containing Arc to draw.
startAngle Angle in degrees where Arc begins.
sweepAngle Sweep angle in degrees; positive is clockwise.
useCenter If true include the center of the oval.
paint Paint stroke or fill, blend, color, and so on, used to draw.

Example

Example

---

drawRoundRect

void drawRoundRect(const SkRect& rect, SkScalar rx, SkScalar ry,
                   const SkPaint& paint)
Draw Round Rect bounded by Rect rect, with corner radii (rx, ry) using Clip, Matrix, and Paint paint. In paint: Paint Style determines if Round Rect is stroked or filled; if stroked, Paint Stroke Width describes the line thickness. If rx or ry are less than zero, they are treated as if they are zero. If rx plus ry exceeds rect width or rect height, radii are scaled down to fit. If rx and ry are zero, Round Rect is drawn as Rect and if stroked is affected by Paint Stroke Join.

Parameters

rect Rect bounds of Round Rect to draw.
rx Semiaxis length in x of oval describing rounded corners.
ry Semiaxis length in y of oval describing rounded corners.
paint Stroke, blend, color, and so on, used to draw.

Example

Top row has a zero radius a generates a rectangle. Second row radii sum to less than sides. Third row radii sum equals sides. Fourth row radii sum exceeds sides; radii are scaled to fit.
---

drawPath

void drawPath(const SkPath& path, const SkPaint& paint)
Draw Path path using Clip, Matrix, and Paint paint. Path contains an array of Path Contour, each of which may be open or closed. In paint: Paint Style determines if Round Rect is stroked or filled: if filled, Path Fill Type determines whether Path Contour describes inside or outside of fill; if stroked, Paint Stroke Width describes the line thickness, Paint Stroke Cap describes line ends, and Paint Stroke Join describes how corners are drawn.

Parameters

path Path to draw.
paint Stroke, blend, color, and so on, used to draw.

Example

Top rows draw stroked path with combinations of joins and caps. The open contour is affected by caps; the closed contour is affected by joins. Bottom row draws fill the same for open and closed contour. First bottom column shows winding fills overlap. Second bottom column shows even odd fills exclude overlap. Third bottom column shows inverse winding fills area outside both contours.
---

Draw Image

drawImage, drawImageRect, and drawImageNine can be called with a bare pointer or a smart pointer as a convenience. The pairs of calls are otherwise identical.

drawImage

void drawImage(const SkImage* image, SkScalar left, SkScalar top,
               const SkPaint* paint = NULL)
Draw Image image, with its top-left corner at (left, top), using Clip, Matrix, and optional Paint paint. If paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If image is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from image bounds. If generated mask extends beyond image bounds, replicate image edge colors, just as Shader made from SkImage::makeShader with SkShader::kClamp TileMode set replicates the image's edge color when it samples outside of its bounds.

Parameters

image Uncompressed rectangular map of pixels.
left Left side of image.
top Top side of image.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.

Example

---
void drawImage(const sk_sp& image, SkScalar left, SkScalar top,
               const SkPaint* paint = NULL)
Draw Image image, with its top-left corner at (left, top), using Clip, Matrix, and optional Paint paint. If Paint paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If image is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from image bounds. If generated mask extends beyond image bounds, replicate image edge colors, just as Shader made from SkImage::makeShader with SkShader::kClamp TileMode set replicates the image's edge color when it samples outside of its bounds.

Parameters

image Uncompressed rectangular map of pixels.
left Left side of image.
top Top side of image.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.

Example

---

Enum SkCanvas::SrcRectConstraint

enum SrcRectConstraint {
kStrict SrcRectConstraint, 
kFast SrcRectConstraint, 
};
SrcRectConstraint controls the behavior at the edge of the Rect src, provided to drawImageRect, trading off speed for precision. Image Filter in Paint may sample multiple pixels in the image. Rect src restricts the bounds of pixels that may be read. Image Filter may slow down if it cannot read outside the bounds, when sampling near the edge of Rect src. SrcRectConstraint specifies whether an Image Filter is allowed to read pixels outside Rect src.

Constants

SkCanvas::kStrict_SrcRectConstraint Requires Image_Filter to respect Rect src,sampling only inside of its bounds, possibly with a performance penalty.
SkCanvas::kFast_SrcRectConstraint Permits Image_Filter to sample outside of Rect srcby half the width of Image Filter, permitting it to run faster but with error at the image edges.

Example

redBorder contains a black and white checkerboard bordered by red. redBorder is drawn scaled by 16 on the left. The middle and right bitmaps are filtered checkboards. Drawing the checkerboard with kStrict SrcRectConstraint shows only a blur of black and white. Drawing the checkerboard with kFast SrcRectConstraint allows red to bleed in the corners.

drawImageRect

void drawImageRect(const SkImage* image, const SkRect& src, const SkRect& dst,
                   const SkPaint* paint,
                   SrcRectConstraint constraint = kStrict_SrcRectConstraint)
Draw Rect src of Image image, scaled and translated to fill Rect dst. Additionally transform draw using Clip, Matrix, and optional Paint paint. If Paint paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If image is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from image bounds. If generated mask extends beyond image bounds, replicate image edge colors, just as Shader made from SkImage::makeShader with SkShader::kClamp TileMode set replicates the image's edge color when it samples outside of its bounds. constraint set to kStrict SrcRectConstraint limits Paint Filter Quality to sample within src; set to kFast SrcRectConstraint allows sampling outside to improve performance.

Parameters

image Image containing pixels, dimensions, and format.
src Source Rect of image to draw from.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.
constraint Filter strictly within src or draw faster.

Example

The left bitmap draws with Paint default kNone SkFilterQuality, and stays within its bounds; there's no bleeding with kFast SrcRectConstraint. the middle and right bitmaps draw with kLow SkFilterQuality; with kStrict SrcRectConstraint, the filter remains within the checkerboard, and with kFast SrcRectConstraint red bleeds on the edges.
---
void drawImageRect(const SkImage* image, const SkIRect& isrc, const SkRect& dst,
                   const SkPaint* paint,
                   SrcRectConstraint constraint = kStrict_SrcRectConstraint)
Draw IRect isrc of Image image, scaled and translated to fill Rect dst. Note that isrc is on integer pixel boundaries; dst may include fractional boundaries. Additionally transform draw using Clip, Matrix, and optional Paint paint. If Paint paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If image is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from image bounds. If generated mask extends beyond image bounds, replicate image edge colors, just as Shader made from SkImage::makeShader with SkShader::kClamp TileMode set replicates the image's edge color when it samples outside of its bounds. constraint set to kStrict SrcRectConstraint limits Paint Filter Quality to sample within src; set to kFast SrcRectConstraint allows sampling outside to improve performance.

Parameters

image Image containing pixels, dimensions, and format.
isrc Source IRect of image to draw from.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.
constraint Filter strictly within src or draw faster.

Example

---
void drawImageRect(const SkImage* image, const SkRect& dst, const SkPaint* paint,
                   SrcRectConstraint constraint = kStrict_SrcRectConstraint)
Draw Image image, scaled and translated to fill Rect dst, using Clip, Matrix, and optional Paint paint. If Paint paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If image is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from image bounds. If generated mask extends beyond image bounds, replicate image edge colors, just as Shader made from SkImage::makeShader with SkShader::kClamp TileMode set replicates the image's edge color when it samples outside of its bounds. Use constaint to choose kStrict SrcRectConstraint or kFast SrcRectConstraint.

Parameters

image Image containing pixels, dimensions, and format.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.
constraint Filter strictly within src or draw faster.

Example

---
void drawImageRect(const sk_sp& image, const SkRect& src,
                   const SkRect& dst, const SkPaint* paint,
                   SrcRectConstraint constraint = kStrict_SrcRectConstraint)
Draw Rect src of Image image, scaled and translated to fill Rect dst. Additionally transform draw using Clip, Matrix, and optional Paint paint. If Paint paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If image is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from image bounds. If generated mask extends beyond image bounds, replicate image edge colors, just as Shader made from SkImage::makeShader with SkShader::kClamp TileMode set replicates the image's edge color when it samples outside of its bounds. constraint set to kStrict SrcRectConstraint limits Paint Filter Quality to sample within src; set to kFast SrcRectConstraint allows sampling outside to improve performance.

Parameters

image Image containing pixels, dimensions, and format.
src Source Rect of image to draw from.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.
constraint Filter strictly within src or draw faster.

Example

Canvas scales and translates; transformation from src to dst also scales. The two matrices are concatenated to create the final transformation.
---
void drawImageRect(const sk_sp& image, const SkIRect& isrc,
                   const SkRect& dst, const SkPaint* paint,
                   SrcRectConstraint constraint = kStrict_SrcRectConstraint)
Draw IRect isrc of Image image, scaled and translated to fill Rect dst. Note that isrc is on integer pixel boundaries; dst may include fractional boundaries. Additionally transform draw using Clip, Matrix, and optional Paint paint. If Paint paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If image is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from image bounds. If generated mask extends beyond image bounds, replicate image edge colors, just as Shader made from SkShader::MakeBitmapShader with SkShader::kClamp TileMode set replicates the image's edge color when it samples outside of its bounds. cons set to kStrict SrcRectConstraint limits Paint Filter Quality to sample within src; set to kFast SrcRectConstraint allows sampling outside to improve performance.

Parameters

image Image containing pixels, dimensions, and format.
isrc Source IRect of image to draw from.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.
constraint Filter strictly within src or draw faster.

Example

---
void drawImageRect(const sk_sp& image, const SkRect& dst,
                   const SkPaint* paint,
                   SrcRectConstraint constraint = kStrict_SrcRectConstraint)
Draw Image image, scaled and translated to fill Rect dst, using Clip, Matrix, and optional Paint paint. If Paint paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If image is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from image bounds. If generated mask extends beyond image bounds, replicate image edge colors, just as Shader made from SkImage::makeShader with SkShader::kClamp TileMode set replicates the image's edge color when it samples outside of its bounds. constraint set to kStrict SrcRectConstraint limits Paint Filter Quality to sample within src; set to kFast SrcRectConstraint allows sampling outside to improve performance.

Parameters

image Image containing pixels, dimensions, and format.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.
constraint Filter strictly within src or draw faster.

Example

---

drawImageNine

void drawImageNine(const SkImage* image, const SkIRect& center,
                   const SkRect& dst, const SkPaint* paint = nullptr)
Draw Image image stretched differentially to fit into Rect dst. IRect center divides the image into nine sections: four sides, four corners, and the center. corners are unscaled or scaled down proportionately if their sides are larger than dst; center and four sides are scaled to fit remaining space, if any. Additionally transform draw using Clip, Matrix, and optional Paint paint. If paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If image is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from image bounds. If generated mask extends beyond image bounds, replicate image edge colors, just as Shader made from SkShader::MakeBitmapShader with SkShader::kClamp TileMode set replicates the image's edge color when it samples outside of its bounds.

Parameters

image Image containing pixels, dimensions, and format.
center IRect edge of image corners and sides.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.

Example

The leftmost image is smaller than center; only corners are drawn, all scaled to fit. The second image equals the size of center; only corners are drawn, unscaled. The remaining images are larger than center. All corners draw unscaled. The sides and center are scaled if needed to take up the remaining space.
---
void drawImageNine(const sk_sp& image, const SkIRect& center,
                   const SkRect& dst, const SkPaint* paint = nullptr)
Draw Image image stretched differentially to fit into Rect dst. IRect center divides the image into nine sections: four sides, four corners, and the center. corners are unscaled or scaled down proportionately if their sides are larger than dst; center and four sides are scaled to fit remaining space, if any. Additionally transform draw using Clip, Matrix, and optional Paint paint. If Paint paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If image is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from image bounds. If generated mask extends beyond image bounds, replicate image edge colors, just as Shader made from SkShader::MakeBitmapShader with SkShader::kClamp TileMode set replicates the image's edge color when it samples outside of its bounds.

Parameters

image Image containing pixels, dimensions, and format.
center IRect edge of image corners and sides.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.

Example

The two leftmost images has four corners and sides to the left and right of center. The leftmost image scales the width of corners proportionately to fit. The third and fourth image corners are unscaled; the sides and center are scaled to fill the remaining space. The rightmost image has four corners scaled vertically to fit, and uses sides above and below center to fill the remaining space.
---

drawBitmap

void drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top,
                const SkPaint* paint = NULL)
Draw Bitmap bitmap, with its top-left corner at (left, top), using Clip, Matrix, and optional Paint paint. If paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If bitmap is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from bitmap bounds. If generated mask extends beyond bitmap bounds, replicate bitmap edge colors, just as Shader made from SkShader::MakeBitmapShader with SkShader::kClamp TileMode set replicates the bitmap's edge color when it samples outside of its bounds.

Parameters

bitmap Bitmap containing pixels, dimensions, and format.
left Left side of bitmap.
top Top side of bitmap.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.

Example

---

drawBitmapRect

void drawBitmapRect(const SkBitmap& bitmap, const SkRect& src, const SkRect& dst,
                    const SkPaint* paint,
                    SrcRectConstraint constraint = kStrict_SrcRectConstraint)
Draw Rect src of Bitmap bitmap, scaled and translated to fill Rect dst. Additionally transform draw using Clip, Matrix, and optional Paint paint. If paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If bitmap is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from bitmap bounds. If generated mask extends beyond bitmap bounds, replicate bitmap edge colors, just as Shader made from SkShader::MakeBitmapShader with SkShader::kClamp TileMode set replicates the bitmap's edge color when it samples outside of its bounds. constraint set to kStrict SrcRectConstraint limits Paint Filter Quality to sample within src; set to kFast SrcRectConstraint allows sampling outside to improve performance.

Parameters

bitmap Bitmap containing pixels, dimensions, and format.
src Source Rect of image to draw from.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.
constraint Filter strictly within src or draw faster.

Example

---
void drawBitmapRect(const SkBitmap& bitmap, const SkIRect& isrc,
                    const SkRect& dst, const SkPaint* paint,
                    SrcRectConstraint constraint = kStrict_SrcRectConstraint)
Draw IRect isrc of Bitmap bitmap, scaled and translated to fill Rect dst. Note that isrc is on integer pixel boundaries; dst may include fractional boundaries. Additionally transform draw using Clip, Matrix, and optional Paint paint. If paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If bitmap is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from bitmap bounds. If generated mask extends beyond bitmap bounds, replicate bitmap edge colors, just as Shader made from SkShader::MakeBitmapShader with SkShader::kClamp TileMode set replicates the bitmap's edge color when it samples outside of its bounds. constraint set to kStrict SrcRectConstraint limits Paint Filter Quality to sample within src; set to kFast SrcRectConstraint allows sampling outside to improve performance.

Parameters

bitmap Bitmap containing pixels, dimensions, and format.
isrc Source IRect of image to draw from.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.
constraint Filter strictly within src or draw faster.

Example

---
void drawBitmapRect(const SkBitmap& bitmap, const SkRect& dst,
                    const SkPaint* paint,
                    SrcRectConstraint constraint = kStrict_SrcRectConstraint)
Draw Bitmap bitmap, scaled and translated to fill Rect dst. Note that isrc is on integer pixel boundaries; dst may include fractional boundaries. Additionally transform draw using Clip, Matrix, and optional Paint paint. If paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If bitmap is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from bitmap bounds. If generated mask extends beyond bitmap bounds, replicate bitmap edge colors, just as Shader made from SkShader::MakeBitmapShader with SkShader::kClamp TileMode set replicates the bitmap's edge color when it samples outside of its bounds. constraint set to kStrict SrcRectConstraint limits Paint Filter Quality to sample within src; set to kFast SrcRectConstraint allows sampling outside to improve performance.

Parameters

bitmap Bitmap containing pixels, dimensions, and format.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.
constraint Filter strictly within src or draw faster.

Example

---

drawBitmapNine

void drawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
                    const SkRect& dst, const SkPaint* paint = NULL)
Draw Bitmap bitmap stretched differentially to fit into Rect dst. IRect center divides the bitmap into nine sections: four sides, four corners, and the center. corners are unscaled or scaled down proportionately if their sides are larger than dst; center and four sides are scaled to fit remaining space, if any. Additionally transform draw using Clip, Matrix, and optional Paint paint. If Paint paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If bitmap is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from bitmap bounds. If generated mask extends beyond bitmap bounds, replicate bitmap edge colors, just as Shader made from SkShader::MakeBitmapShader with SkShader::kClamp TileMode set replicates the bitmap's edge color when it samples outside of its bounds.

Parameters

bitmap Bitmap containing pixels, dimensions, and format.
center IRect edge of image corners and sides.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.

Example

The two leftmost bitmap draws has four corners and sides to the left and right of center. The leftmost bitmap draw scales the width of corners proportionately to fit. The third and fourth draw corners are unscaled; the sides and center are scaled to fill the remaining space. The rightmost bitmap draw has four corners scaled vertically to fit, and uses sides above and below center to fill the remaining space.
---

Struct SkCanvas::Lattice

Lattice divides Bitmap or Image into a rectangular grid. Grid entries on even columns and even rows are fixed; these entries are always drawn at their original size if the destination is large enough. If the destination side is too small to hold the fixed entries, all fixed entries are proportionately scaled down to fit. The grid entries not on even columns and rows are scaled to fit the remaining space, if any.

struct Lattice {
enum Flags {...

const int*     fXDivs;
const int*     fYDivs;
const Flags*   fFlags;
int            fXCount;
int            fYCount;
const SkIRect* fBounds;
};

Enum SkCanvas::Lattice::Flags

enum Flags : uint8_t {
kTransparent Flags = 1 << 0,
};
Optional setting per rectangular grid entry to make it transparent.

Constants

SkCanvas::Lattice::kTransparent_Flags 1Set to skip lattice rectangle by making it transparent.
const int* fXDivs Array of x-coordinates that divide the bitmap vertically. Array entries must be unique, increasing, greater than or equal to fBounds left edge, and less than fBounds right edge. Set the first element to fBounds left to collapse the left column of fixed grid entries. const int* fYDivs Array of y-coordinates that divide the bitmap horizontally. Array entries must be unique, increasing, greater than or equal to fBounds top edge, and less than fBounds bottom edge. Set the first element to fBounds top to collapse the top row of fixed grid entries. const Flags* fFlags Optional array of Flags, one per rectangular grid entry: array length must be (fXCount + 1) * (fYCount + 1). Array entries correspond to the rectangular grid entries, ascending left to right and then top to bottom. int fXCount Number of entries in fXDivs array; one less than the number of horizontal divisions. int fYCount Number of entries in fYDivs array; one less than the number of vertical divisions. const SkIRect* fBounds Optional subset IRect source to draw from. If nullptr, source bounds is dimensions of Bitmap or Image.

drawBitmapLattice

void drawBitmapLattice(const SkBitmap& bitmap, const Lattice& lattice,
                       const SkRect& dst, const SkPaint* paint = nullptr)
Draw Bitmap bitmap stretched differentially to fit into Rect dst. Lattice lattice divides bitmap into a rectangular grid. Each intersection of an even-numbered row and column is fixed; like the corners of drawBitmapNine, fixed lattice elements never scale larger than their initial size and shrink proportionately when all fixed elements exceed the bitmap's dimension. All other grid elements scale to fill the available space, if any. Additionally transform draw using Clip, Matrix, and optional Paint paint. If Paint paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If bitmap is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from bitmap bounds. If generated mask extends beyond bitmap bounds, replicate bitmap edge colors, just as Shader made from SkShader::MakeBitmapShader with SkShader::kClamp TileMode set replicates the bitmap's edge color when it samples outside of its bounds.

Parameters

bitmap Bitmap containing pixels, dimensions, and format.
lattice Division of bitmap into fixed and variable rectangles.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.

Example

The two leftmost bitmap draws has four corners and sides to the left and right of center. The leftmost bitmap draw scales the width of corners proportionately to fit. The third and fourth draw corners are unscaled; the sides are scaled to fill the remaining space; the center is transparent. The rightmost bitmap draw has four corners scaled vertically to fit, and uses sides above and below center to fill the remaining space.
---

drawImageLattice

void drawImageLattice(const SkImage* image, const Lattice& lattice,
                      const SkRect& dst, const SkPaint* paint = nullptr)
Draw Image image stretched differentially to fit into Rect dst. Lattice lattice divides image into a rectangular grid. Each intersection of an even-numbered row and column is fixed; like the corners of drawImageNine, fixed lattice elements never scale larger than their initial size and shrink proportionately when all fixed elements exceed the bitmap's dimension. All other grid elements scale to fill the available space, if any. Additionally transform draw using Clip, Matrix, and optional Paint paint. If Paint paint is supplied, apply Color Filter, Color Alpha, Image Filter, Blend Mode, and Draw Looper. If image is kAlpha 8 SkColorType, apply Shader. if paint contains Mask Filter, generate mask from image bounds. If generated mask extends beyond image bounds, replicate image edge colors, just as Shader made from SkShader::MakeBitmapShader with SkShader::kClamp TileMode set replicates the image's edge color when it samples outside of its bounds.

Parameters

image Image containing pixels, dimensions, and format.
lattice Division of bitmap into fixed and variable rectangles.
dst Destination Rect of image to draw to.
paint Paint containing Blend Mode, Color Filter, Image Filter, and so on; or nullptr.

Example

The leftmost image is smaller than center; only corners are drawn, all scaled to fit. The second image equals the size of center; only corners are drawn, unscaled. The remaining images are larger than center. All corners draw unscaled. The sides are scaled if needed to take up the remaining space; the center is transparent.
---

drawText

void drawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
              const SkPaint& paint)
Draw text, with origin at (x, y), using Clip, Matrix, and Paint paint. text's meaning depends on Paint Text Encoding; by default, text encoding is UTF-8. x and y meaning depends on Paint Text Align and Paint Vertical Text; by default text draws left to right, positioning the first glyph's left side bearing at x and its baseline at y. Text size is affected by Matrix and Paint Text Size. All elements of paint: Path Effect, Rasterizer, Mask Filter, Shader, Color Filter, Image Filter, and Draw Looper; apply to text. By default, drawText draws filled 12 point black glyphs.

Parameters

text Character code points or glyphs drawn.
byteLength Byte length of text array.
x Start of text on x-axis.
y Start of text on y-axis.
paint Text size, blend, color, and so on, used to draw.

Example

The same text is drawn varying Paint Text Size and varying Matrix.
---

drawString

void drawString(const char* string, SkScalar x, SkScalar y, const SkPaint& paint)
Draw null terminated string, with origin at (x, y), using Clip, Matrix, and Paint paint. string's meaning depends on Paint Text Encoding; by default, string encoding is UTF-8. Other values of Paint Text Encoding are unlikely to produce the desired results, since zero bytes may be embedded in the string. x and y meaning depends on Paint Text Align and Paint Vertical Text; by default string draws left to right, positioning the first glyph's left side bearing at x and its baseline at y. Text size is affected by Matrix and Paint Text Size. All elements of paint: Path Effect, Rasterizer, Mask Filter, Shader, Color Filter, Image Filter, and Draw Looper; apply to string. By default, drawString draws filled 12 point black glyphs.

Parameters

string Character code points or glyphs drawn, ending with a char value of zero.
x Start of string on x-axis.
y Start of string on y-axis.
paint Text size, blend, color, and so on, used to draw.

Example

See Also

drawText ---

void drawString(const SkString& string, SkScalar x, SkScalar y,
                const SkPaint& paint)
Draw null terminated string, with origin at (x, y), using Clip, Matrix, and Paint paint. string's meaning depends on Paint Text Encoding; by default, string encoding is UTF-8. Other values of Paint Text Encoding are unlikely to produce the desired results, since zero bytes may be embedded in the string. x and y meaning depends on Paint Text Align and Paint Vertical Text; by default string draws left to right, positioning the first glyph's left side bearing at x and its baseline at y. Text size is affected by Matrix and Paint Text Size. All elements of paint: Path Effect, Rasterizer, Mask Filter, Shader, Color Filter, Image Filter, and Draw Looper; apply to string. By default, drawString draws filled 12 point black glyphs.

Parameters

string Character code points or glyphs drawn, ending with a char value of zero.
x Start of string on x-axis.
y Start of string on y-axis.
paint Text size, blend, color, and so on, used to draw.

Example

See Also

drawText ---

drawPosText

void drawPosText(const void* text, size_t byteLength, const SkPoint pos[],
                 const SkPaint& paint)
Draw each glyph in text with the origin in pos array, using Clip, Matrix, and Paint paint. The number of entries in pos array must match the number of glyphs described by byteLength of text. text's meaning depends on Paint Text Encoding; by default, text encoding is UTF-8. pos elements' meaning depends on Paint Text Align and Paint Vertical Text; by default each glyph's left side bearing is positioned at x and its baseline is positioned at y. Text size is affected by Matrix and Paint Text Size. All elements of paint: Path Effect, Rasterizer, Mask Filter, Shader, Color Filter, Image Filter, and Draw Looper; apply to text. By default, drawPosText draws filled 12 point black glyphs. Layout engines such as Harfbuzz typically use drawPosText to position each glyph rather than using the font's advance widths.

Parameters

text Character code points or glyphs drawn.
byteLength Byte length of text array.
pos Array of glyph origins.
paint Text size, blend, color, and so on, used to draw.

Example

---

drawPosTextH

void drawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[],
                  SkScalar constY, const SkPaint& paint)
Draw each glyph in text with its (x, y) origin composed from xpos array and constY, using Clip, Matrix, and Paint paint. The number of entries in xpos array must match the number of glyphs described by byteLength of text. text's meaning depends on Paint Text Encoding; by default, text encoding is UTF-8. pos elements' meaning depends on Paint Text Align and Paint Vertical Text; by default each glyph's left side bearing is positioned at an xpos element and its baseline is positioned at constY. Text size is affected by Matrix and Paint Text Size. All elements of paint: Path Effect, Rasterizer, Mask Filter, Shader, Color Filter, Image Filter, and Draw Looper; apply to text. By default, drawPosTextH draws filled 12 point black glyphs. Layout engines such as Harfbuzz typically use drawPosTextH to position each glyph rather than using the font's advance widths if all glyphs share the same baseline.

Parameters

text Character code points or glyphs drawn.
byteLength Byte length of text array.
xpos Array of x positions, used to position each glyph.
constY Shared y coordinate for all of x positions.
paint Text size, blend, color, and so on, used to draw.

Example

---

drawTextOnPathHV

void drawTextOnPathHV(const void* text, size_t byteLength, const SkPath& path,
                      SkScalar hOffset, SkScalar vOffset, const SkPaint& paint)
Draw text on Path path, using Clip, Matrix, and Paint paint. Origin of text is at distance hOffset along the path, offset by a perpendicular vector of length vOffset. If the path section corresponding the glyph advance is curved, the glyph is drawn curved to match; control points in the glyph are mapped to projected points parallel to the path. If the text's advance is larger than the path length, the excess text is clipped. text's meaning depends on Paint Text Encoding; by default, text encoding is UTF-8. Origin meaning depends on Paint Text Align and Paint Vertical Text; by default text positions the first glyph's left side bearing at origin x and its baseline at origin y. Text size is affected by Matrix and Paint Text Size. All elements of paint: Path Effect, Rasterizer, Mask Filter, Shader, Color Filter, Image Filter, and Draw Looper; apply to text. By default, drawTextOnPathHV draws filled 12 point black glyphs.

Parameters

text Character code points or glyphs drawn.
byteLength Byte length of text array.
path Path providing text baseline.
hOffset Distance along path to offset origin.
vOffset Offset of text above (if negative) or below (if positive) the path.
paint Text size, blend, color, and so on, used to draw.

Example

---

drawTextOnPath

void drawTextOnPath(const void* text, size_t byteLength, const SkPath& path,
                    const SkMatrix* matrix, const SkPaint& paint)
Draw text on Path path, using Clip, Matrix, and Paint paint. Origin of text is at beginning of path offset by matrix, if provided, before it is mapped to path. If the path section corresponding the glyph advance is curved, the glyph is drawn curved to match; control points in the glyph are mapped to projected points parallel to the path. If the text's advance is larger than the path length, the excess text is clipped. text's meaning depends on Paint Text Encoding; by default, text encoding is UTF-8. Origin meaning depends on Paint Text Align and Paint Vertical Text; by default text positions the first glyph's left side bearing at origin x and its baseline at origin y. Text size is affected by Matrix and Paint Text Size. All elements of paint: Path Effect, Rasterizer, Mask Filter, Shader, Color Filter, Image Filter, and Draw Looper; apply to text. By default, drawTextOnPath draws filled 12 point black glyphs.

Parameters

text Character code points or glyphs drawn.
byteLength Byte length of text array.
path Path providing text baseline.
matrix Optional transform of glyphs before mapping to path; or nullptr.
paint Text size, blend, color, and so on, used to draw.

Example

---

drawTextRSXform

void drawTextRSXform(const void* text, size_t byteLength,
                     const SkRSXform xform[], const SkRect* cullRect,
                     const SkPaint& paint)
Draw text, transforming each glyph by the corresponding SkRSXform, using Clip, Matrix, and Paint paint. RSXform array specifies a separate square scale, rotation, and translation for each glyph. Optional Rect cullRect is a conservative bounds of text, taking into account RSXform and paint. If cullrect is outside of Clip, canvas can skip drawing. All elements of paint: Path Effect, Rasterizer, Mask Filter, Shader, Color Filter, Image Filter, and Draw Looper; apply to text. By default, drawTextRSXform draws filled 12 point black glyphs.

Parameters

text Character code points or glyphs drawn.
byteLength Byte length of text array.
xform RSXform rotates, scales, and translates each glyph individually.
cullRect Rect bounds of text for efficient clipping; or nullptr.
paint Text size, blend, color, and so on, used to draw.

Example

---

drawTextBlob

void drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
                  const SkPaint& paint)
Draw Text Blob blob at (x, y), using Clip, Matrix, and Paint paint. blob contains glyphs, their positions, and paint attributes specific to text: Typeface, Paint Text Size, Paint Text Scale X, Paint Text Skew X, Paint Text Align, Paint Hinting, Anti-alias, Paint Fake Bold, Font Embedded Bitmaps, Full Hinting Spacing, LCD Text, Linear Text, Subpixel Text, and Paint Vertical Text. Elements of paint: Path Effect, Rasterizer, Mask Filter, Shader, Color Filter, Image Filter, and Draw Looper; apply to blob.

Parameters

blob Glyphs, positions, and their paints' text size, typeface, and so on.
x Horizontal offset applied to blob.
y Vertical offset applied to blob.
paint Blend, color, stroking, and so on, used to draw.

Example

---
void drawTextBlob(const sk_sp& blob, SkScalar x, SkScalar y,
                  const SkPaint& paint)
Draw Text Blob blob at (x, y), using Clip, Matrix, and Paint paint. blob contains glyphs, their positions, and paint attributes specific to text: Typeface, Paint Text Size, Paint Text Scale X, Paint Text Skew X, Paint Text Align, Paint Hinting, Anti-alias, Paint Fake Bold, Font Embedded Bitmaps, Full Hinting Spacing, LCD Text, Linear Text, Subpixel Text, and Paint Vertical Text. Elements of paint: Path Effect, Rasterizer, Mask Filter, Shader, Color Filter, Image Filter, and Draw Looper; apply to blob.

Parameters

blob Glyphs, positions, and their paints' text size, typeface, and so on.
x Horizontal offset applied to blob.
y Vertical offset applied to blob.
paint Blend, color, stroking, and so on, used to draw.

Example

Paint attributes unrelated to text, like color, have no effect on paint in allocated Text Blob. Paint attributes related to text, like text size, have no effect on paint passed to drawTextBlob.
---

drawPicture

void drawPicture(const SkPicture* picture)
Draw Picture picture, using Clip and Matrix. Clip and Matrix are unchanged by picture contents, as if save was called before and restore was called after drawPicture. Picture records a series of draw commands for later playback.

Parameters

picture Recorded drawing commands to play.

Example

---
void drawPicture(const sk_sp& picture)
Draw Picture picture, using Clip and Matrix. Clip and Matrix are unchanged by picture contents, as if save was called before and restore was called after drawPicture. Picture records a series of draw commands for later playback.

Parameters

picture Recorded drawing commands to play.

Example

---
void drawPicture(const SkPicture* picture, const SkMatrix* matrix,
                 const SkPaint* paint)
Draw Picture picture, using Clip and Matrix; transforming picture with Matrix matrix, if provided; and use Paint paint Color Alpha, Color Filter, Image Filter, and Blend Mode, if provided. matrix transformation is equivalent to: save, concat, drawPicture, restore. paint use is equivalent to: saveLayer, drawPicture, restore.

Parameters

picture Recorded drawing commands to play.
matrix Optional Matrix to rotate, scale, translate, and so on; or nullptr.
paint Optional Paint to apply transparency, filtering, and so on; or nullptr.

Example

---
void drawPicture(const sk_sp& picture, const SkMatrix* matrix,
                 const SkPaint* paint)
Draw Picture picture, using Clip and Matrix; transforming picture with Matrix matrix, if provided; and use Paint paint Color Alpha, Color Filter, Image Filter, and Blend Mode, if provided. matrix transformation is equivalent to: save, concat, drawPicture, restore. paint use is equivalent to: saveLayer, drawPicture, restore.

Parameters

picture Recorded drawing commands to play.
matrix Optional Matrix to rotate, scale, translate, and so on; or nullptr.
paint Optional Paint to apply transparency, filtering, and so on; or nullptr.

Example

---

drawVertices

void drawVertices(const SkVertices* vertices, SkBlendMode mode,
                  const SkPaint& paint)
Draw Vertices vertices, a triangle mesh, using Clip and Matrix. If Vertices Texs and Vertices Colors are defined in vertices, and Paint paint contains Shader, Blend Mode mode combines Vertices Colors with Shader.

Parameters

vertices The triangle mesh to draw.
mode Combines Vertices Colors with Shader, if both are present.
paint Specifies the Shader, used as Vertices texture, if present.

Example

---
void drawVertices(const sk_sp& vertices, SkBlendMode mode,
                  const SkPaint& paint)
Draw Vertices vertices, a triangle mesh, using Clip and Matrix. If Vertices Texs and Vertices Colors are defined in vertices, and Paint paint contains Shader, Blend Mode mode combines Vertices Colors with Shader.

Parameters

vertices The triangle mesh to draw.
mode Combines Vertices Colors with Shader, if both are present.
paint Specifies the Shader, used as Vertices texture, if present.

Example

---

drawPatch

void drawPatch(const SkPoint cubics[12], const SkColor colors[4],
               const SkPoint texCoords[4], SkBlendMode mode,
               const SkPaint& paint)
Draw a cubic Coons patch: the interpolation of four cubics with shared corners, associating a color, and optionally a texture coordinate, with each corner. The Coons patch uses Clip and Matrix, Paint paint's Shader, Color Filter, Color Alpha, Image Filter, and Blend Mode. If Shader is provided it is treated as the Coons patch texture; Blend Mode mode combines Color colors and Shader if both are provided.

Parameters

cubics Point array cubics specifying the four cubics starting at the top left corner,
colors Color array color associating colors with corners in top left, top right, bottom right,
texCoords Point array texCoords mapping Shader as texture to corners in same order, if paint
mode Blend Mode for colors and Shader if present.
paint Shader, Color Filter, Blend Mode, used to draw.

Example

---
void drawPatch(const SkPoint cubics[12], const SkColor colors[4],
               const SkPoint texCoords[4], const SkPaint& paint)
Draw a cubic Coons patch: the interpolation of four cubics with shared corners, associating a color, a texture coordinate, or both, with each corner. The Coons patch uses Clip and Matrix, Paint paint's Shader, Color Filter, Color Alpha, Image Filter, (?) and Blend Mode. If Shader is provided it is treated as the Coons patch texture.

Parameters

cubics Point array cubics specifying the four cubics starting at the top left corner,
colors Color array color associating colors with corners in top left, top right, bottom right,
texCoords Point array texCoords mapping Shader as texture to corners in same order, if paint
paint Shader, Color Filter, Blend Mode, used to draw.

Example

Example

---

drawAtlas

void drawAtlas(const SkImage* atlas, const SkRSXform xform[], const SkRect tex[],
               const SkColor colors[], int count, SkBlendMode mode,
               const SkRect* cullRect, const SkPaint* paint)
Draw a set of sprites from atlas, using Clip, Matrix, and optional Paint paint. paint uses Anti-alias, Color Alpha, Color Filter, Image Filter, and Blend Mode to draw, if present. For each entry in the array, Rect tex locates sprite in atlas, and RSXform xform transforms it into destination space. xform, text, and colors if present, must contain count entries. Optional colors is applied for each sprite using Blend Mode. Optional cullRect is a conservative bounds of all transformed sprites. If cullrect is outside of Clip, canvas can skip drawing.

Parameters

atlas Image containing sprites.
xform RSXform mappings for sprites in atlas.
tex Rect locations of sprites in atlas.
colors Color, one per sprite, blended with sprite using Blend Mode; or nullptr.
count Number of sprites to draw.
mode Blend Mode combining colors and sprites.
cullRect Rect bounds of transformed sprites for efficient clipping; or nullptr.
paint Paint Color Filter, Image Filter, Blend Mode, and so on; or nullptr.

Example

---
void drawAtlas(const sk_sp& atlas, const SkRSXform xform[],
               const SkRect tex[], const SkColor colors[], int count,
               SkBlendMode mode, const SkRect* cullRect, const SkPaint* paint)
Draw a set of sprites from atlas, using Clip, Matrix, and optional Paint paint. paint uses Anti-alias, Color Alpha, Color Filter, Image Filter, and Blend Mode to draw, if present. For each entry in the array, Rect tex locates sprite in atlas, and RSXform xform transforms it into destination space. xform, text, and colors if present, must contain count entries. Optional colors is applied for each sprite using Blend Mode. Optional cullRect is a conservative bounds of all transformed sprites. If cullrect is outside of Clip, canvas can skip drawing.

Parameters

atlas Image containing sprites.
xform RSXform mappings for sprites in atlas.
tex Rect locations of sprites in atlas.
colors Color, one per sprite, blended with sprite using Blend Mode; or nullptr.
count Number of sprites to draw.
mode Blend Mode combining colors and sprites.
cullRect Rect bounds of transformed sprites for efficient clipping; or nullptr.
paint Paint Color Filter, Image Filter, Blend Mode, and so on; or nullptr.

Example

---
void drawAtlas(const SkImage* atlas, const SkRSXform xform[], const SkRect tex[],
               int count, const SkRect* cullRect, const SkPaint* paint)
Draw a set of sprites from atlas, using Clip, Matrix, and optional Paint paint. paint uses Anti-alias, Color Alpha, Color Filter, Image Filter, and Blend Mode to draw, if present. For each entry in the array, Rect tex locates sprite in atlas, and RSXform xform transforms it into destination space. xform and text must contain count entries. Optional cullRect is a conservative bounds of all transformed sprites. If cullrect is outside of Clip, canvas can skip drawing.

Parameters

atlas Image containing sprites.
xform RSXform mappings for sprites in atlas.
tex Rect locations of sprites in atlas.
count Number of sprites to draw.
cullRect Rect bounds of transformed sprites for efficient clipping; or nullptr.
paint Paint Color Filter, Image Filter, Blend Mode, and so on; or nullptr.

Example

---
void drawAtlas(const sk_sp& atlas, const SkRSXform xform[],
               const SkRect tex[], int count, const SkRect* cullRect,
               const SkPaint* paint)
Draw a set of sprites from atlas, using Clip, Matrix, and optional Paint paint. paint uses Anti-alias, Color Alpha, Color Filter, Image Filter, and Blend Mode to draw, if present. For each entry in the array, Rect tex locates sprite in atlas, and RSXform xform transforms it into destination space. xform and text must contain count entries. Optional cullRect is a conservative bounds of all transformed sprites. If cullrect is outside of Clip, canvas can skip drawing.

Parameters

atlas Image containing sprites.
xform RSXform mappings for sprites in atlas.
tex Rect locations of sprites in atlas.
count Number of sprites to draw.
cullRect Rect bounds of transformed sprites for efficient clipping; or nullptr.
paint Paint Color Filter, Image Filter, Blend Mode, and so on; or nullptr.

Example

---

drawDrawable

void drawDrawable(SkDrawable* drawable, const SkMatrix* matrix = NULL)
Draw Drawable drawable using Clip and Matrix, concatenated with optional matrix. If Canvas has an asynchronous implementation, as is the case when it is recording into Picture, then drawable will be referenced, so that SkDrawable::draw() can be called when the operation is finalized. To force immediate drawing, call SkDrawable::draw() instead.

Parameters

drawable Custom struct encapsulating drawing commands.
matrix Transformation applied to drawing; or nullptr.

Example

---
void drawDrawable(SkDrawable* drawable, SkScalar x, SkScalar y)
Draw Drawable drawable using Clip and Matrix, offset by (x, y). If Canvas has an asynchronous implementation, as is the case when it is recording into Picture, then drawable will be referenced, so that SkDrawable::draw() can be called when the operation is finalized. To force immediate drawing, call SkDrawable::draw() instead.

Parameters

drawable Custom struct encapsulating drawing commands.
x Offset into Canvas writable pixels in x.
y Offset into Canvas writable pixels in y.

Example

---

drawAnnotation

void drawAnnotation(const SkRect& rect, const char key[], SkData* value)
Associate Rect on Canvas when an annotation; a key-value pair, where the key is a null-terminated utf8 string, and optional value is stored as Data. Only some canvas implementations, such as recording to Picture, or drawing to Document PDF, use annotations.

Parameters

rect Rect extent of canvas to annotate.
key String used for lookup.
value Data holding value stored in annotation.

Example

---
void drawAnnotation(const SkRect& rect, const char key[],
                    const sk_sp& value)
Associate Rect on Canvas when an annotation; a key-value pair, where the key is a null-terminated utf8 string, and optional value is stored as Data. Only some canvas implementations, such as recording to Picture, or drawing to Document PDF, use annotations.

Parameters

rect Rect extent of canvas to annotate.
key String used for lookup.
value Data holding value stored in annotation.

Example

---

getDrawFilter

SkDrawFilter* getDrawFilter() const
Legacy call to be deprecated. ---

setDrawFilter

virtual SkDrawFilter* setDrawFilter(SkDrawFilter* filter)
Legacy call to be deprecated. ---

isClipEmpty

virtual bool isClipEmpty() const
Returns true if Clip is empty; that is, nothing will draw. isClipEmpty may do work when called; it should not be called more often than needed. However, once called, subsequent calls perform no work until Clip changes.

Return Value

true if Clip is empty.

Example

Example Output

~~~~ clip is not empty clip is empty ~~~~

---

isClipRect

virtual bool isClipRect() const
Returns true if Clip is Rect and not empty. Returns false if the clip is empty, or if it is not Rect.

Return Value

true if Clip is Rect and not empty.

Example

Example Output

~~~~ clip is rect clip is not rect ~~~~

---