1 /*
2  * Copyright 2006 The Android Open Source Project
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #ifndef SkCanvas_DEFINED
9 #define SkCanvas_DEFINED
10 
11 #include "SkBlendMode.h"
12 #include "SkClipOp.h"
13 #include "SkDeque.h"
14 #include "SkPaint.h"
15 #include "SkRasterHandleAllocator.h"
16 #include "SkSurfaceProps.h"
17 
18 class GrContext;
19 class GrRenderTargetContext;
20 class SkAndroidFrameworkUtils;
21 class SkBaseDevice;
22 class SkBitmap;
23 class SkClipStack;
24 class SkData;
25 class SkDraw;
26 class SkDrawable;
27 class SkDrawFilter;
28 struct SkDrawShadowRec;
29 class SkImage;
30 class SkImageFilter;
31 class SkMetaData;
32 class SkPath;
33 class SkPicture;
34 class SkPixmap;
35 class SkRasterClip;
36 class SkRegion;
37 class SkRRect;
38 struct SkRSXform;
39 class SkSurface;
40 class SkSurface_Base;
41 class SkTextBlob;
42 class SkVertices;
43 
44 /** \class SkCanvas
45     SkCanvas provides an interface for drawing, and how the drawing is clipped and transformed.
46     SkCanvas contains a stack of SkMatrix and clip values.
47 
48     SkCanvas and SkPaint together provide the state to draw into SkSurface or SkBaseDevice.
49     Each SkCanvas draw call transforms the geometry of the object by the concatenation of all
50     SkMatrix values in the stack. The transformed geometry is clipped by the intersection
51     of all of clip values in the stack. The SkCanvas draw calls use SkPaint to supply drawing
52     state such as color, SkTypeface, text size, stroke width, SkShader and so on.
53 
54     To draw to a pixel-based destination, create raster surface or GPU surface.
55     Request SkCanvas from SkSurface to obtain the interface to draw.
56     SkCanvas generated by raster surface draws to memory visible to the CPU.
57     SkCanvas generated by GPU surface uses Vulkan or OpenGL to draw to the GPU.
58 
59     To draw to a document, obtain SkCanvas from svg canvas, document pdf, or SkPictureRecorder.
60     SkDocument based SkCanvas and other SkCanvas Subclasses reference SkBaseDevice describing the
61     destination.
62 
63     SkCanvas can be constructed to draw to SkBitmap without first creating raster surface.
64     This approach may be deprecated in the future.
65 */
66 class SK_API SkCanvas : SkNoncopyable {
67     enum PrivateSaveLayerFlags {
68         kDontClipToLayer_PrivateSaveLayerFlag   = 1U << 31,
69     };
70 
71 public:
72 
73     /** Allocates raster SkCanvas that will draw directly into pixels.
74 
75         SkCanvas is returned if all parameters are valid.
76         Valid parameters include:
77         info dimensions are zero or positive;
78         info contains SkColorType and SkAlphaType supported by raster surface;
79         pixels is not nullptr;
80         rowBytes is zero or large enough to contain info width pixels of SkColorType.
81 
82         Pass zero for rowBytes to compute rowBytes from info width and size of pixel.
83         If rowBytes is greater than zero, it must be equal to or greater than
84         info width times bytes required for SkColorType.
85 
86         Pixel buffer size should be info height times computed rowBytes.
87         Pixels are not initialized.
88         To access pixels after drawing, call flush() or peekPixels().
89 
90         @param info      width, height, SkColorType, SkAlphaType, SkColorSpace, of raster surface;
91                          width, or height, or both, may be zero
92         @param pixels    pointer to destination pixels buffer
93         @param rowBytes  interval from one SkSurface row to the next, or zero
94         @param props     LCD striping orientation and setting for device independent fonts;
95                          may be nullptr
96         @return          SkCanvas if all parameters are valid; otherwise, nullptr
97     */
98     static std::unique_ptr<SkCanvas> MakeRasterDirect(const SkImageInfo& info, void* pixels,
99                                                       size_t rowBytes,
100                                                       const SkSurfaceProps* props = nullptr);
101 
102     /** Allocates raster SkCanvas specified by inline image specification. Subsequent SkCanvas
103         calls draw into pixels.
104         SkColorType is set to kN32_SkColorType.
105         SkAlphaType is set to kPremul_SkAlphaType.
106         To access pixels after drawing, call flush() or peekPixels().
107 
108         SkCanvas is returned if all parameters are valid.
109         Valid parameters include:
110         width and height are zero or positive;
111         pixels is not nullptr;
112         rowBytes is zero or large enough to contain width pixels of kN32_SkColorType.
113 
114         Pass zero for rowBytes to compute rowBytes from width and size of pixel.
115         If rowBytes is greater than zero, it must be equal to or greater than
116         width times bytes required for SkColorType.
117 
118         Pixel buffer size should be height times rowBytes.
119 
120         @param width     pixel column count on raster surface created; must be zero or greater
121         @param height    pixel row count on raster surface created; must be zero or greater
122         @param pixels    pointer to destination pixels buffer; buffer size should be height
123                          times rowBytes
124         @param rowBytes  interval from one SkSurface row to the next, or zero
125         @return          SkCanvas if all parameters are valid; otherwise, nullptr
126     */
MakeRasterDirectN32(int width,int height,SkPMColor * pixels,size_t rowBytes)127     static std::unique_ptr<SkCanvas> MakeRasterDirectN32(int width, int height, SkPMColor* pixels,
128                                                          size_t rowBytes) {
129         return MakeRasterDirect(SkImageInfo::MakeN32Premul(width, height), pixels, rowBytes);
130     }
131 
132     /** Creates an empty SkCanvas with no backing device or pixels, with
133         a width and height of zero.
134 
135         @return  empty SkCanvas
136     */
137     SkCanvas();
138 
139     /** Creates SkCanvas of the specified dimensions without a SkSurface.
140         Used by Subclasses with custom implementations for draw methods.
141 
142         If props equals nullptr, SkSurfaceProps are created with
143         SkSurfaceProps::InitType settings, which choose the pixel striping
144         direction and order. Since a platform may dynamically change its direction when
145         the device is rotated, and since a platform may have multiple monitors with
146         different characteristics, it is best not to rely on this legacy behavior.
147 
148         @param width   zero or greater
149         @param height  zero or greater
150         @param props   LCD striping orientation and setting for device independent fonts;
151                        may be nullptr
152         @return        SkCanvas placeholder with dimensions
153     */
154     SkCanvas(int width, int height, const SkSurfaceProps* props = nullptr);
155 
156     /** To be deprecated soon.
157     */
158     explicit SkCanvas(SkBaseDevice* device);
159 
160     /** Construct a canvas that draws into bitmap.
161         Sets SkSurfaceProps::kLegacyFontHost_InitType in constructed SkSurface.
162 
163         SkBitmap is copied so that subsequently editing bitmap will not affect
164         constructed SkCanvas.
165 
166         May be deprecated in the future.
167 
168         @param bitmap  width, height, SkColorType, SkAlphaType, and pixel
169                        storage of raster surface
170         @return        SkCanvas that can be used to draw into bitmap
171     */
172     explicit SkCanvas(const SkBitmap& bitmap);
173 
174 #ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
175     enum class ColorBehavior {
176         kLegacy, //!< Is a placeholder to allow specialized constructor; has no meaning.
177     };
178 
179     /** Android framework only.
180 
181         @param bitmap    specifies a bitmap for the canvas to draw into
182         @param behavior  specializes this constructor; value is unused
183         @return          SkCanvas that can be used to draw into bitmap
184     */
185     SkCanvas(const SkBitmap& bitmap, ColorBehavior behavior);
186 #endif
187 
188     /** Construct a canvas that draws into bitmap.
189         Use props to match the device characteristics, like LCD striping.
190 
191         bitmap is copied so that subsequently editing bitmap will not affect
192         constructed SkCanvas.
193 
194         @param bitmap  width, height, SkColorType, SkAlphaType,
195                        and pixel storage of raster surface
196         @param props   order and orientation of RGB striping; and whether to use
197                        device independent fonts
198         @return        SkCanvas that can be used to draw into bitmap
199     */
200     SkCanvas(const SkBitmap& bitmap, const SkSurfaceProps& props);
201 
202     /** Draws saved layer, if any.
203         Frees up resources used by SkCanvas.
204     */
205     virtual ~SkCanvas();
206 
207     /** Returns storage to associate additional data with the canvas.
208         The storage is freed when SkCanvas is deleted.
209 
210         @return  storage that can be read from and written to
211     */
212     SkMetaData& getMetaData();
213 
214     /** Returns SkImageInfo for SkCanvas. If SkCanvas is not associated with raster surface or
215         GPU surface, returned SkColorType is set to kUnknown_SkColorType.
216 
217         @return  dimensions and SkColorType of SkCanvas
218     */
219     SkImageInfo imageInfo() const;
220 
221     /** If SkCanvas is associated with raster surface or
222         GPU surface, copies SkSurfaceProps and returns true. Otherwise,
223         return false and leave props unchanged.
224 
225         @param props  storage for writable SkSurfaceProps
226         @return       true if SkSurfaceProps was copied
227     */
228     bool getProps(SkSurfaceProps* props) const;
229 
230     /** Triggers the immediate execution of all pending draw operations.
231         If SkCanvas is associated with GPU surface, resolves all pending GPU operations.
232         If SkCanvas is associated with raster surface, has no effect; raster draw
233         operations are never deferred.
234     */
235     void flush();
236 
237     /** Gets the size of the base or root layer in global canvas coordinates. The
238         origin of the base layer is always (0,0). The area available for drawing may be
239         smaller (due to clipping or saveLayer).
240 
241         @return  integral width and height of base layer
242     */
243     virtual SkISize getBaseLayerSize() const;
244 
245     /** Creates SkSurface matching info and props, and associates it with SkCanvas.
246         Returns nullptr if no match found.
247 
248         If props is nullptr, matches SkSurfaceProps in SkCanvas. If props is nullptr and SkCanvas
249         does not have SkSurfaceProps, creates SkSurface with default SkSurfaceProps.
250 
251         @param info   width, height, SkColorType, SkAlphaType, and SkColorSpace
252         @param props  SkSurfaceProps to match; may be nullptr to match SkCanvas
253         @return       SkSurface matching info and props, or nullptr if no match is available
254     */
255     sk_sp<SkSurface> makeSurface(const SkImageInfo& info, const SkSurfaceProps* props = nullptr);
256 
257     /** Returns GPU context of the GPU surface associated with SkCanvas.
258 
259         @return  GPU context, if available; nullptr otherwise
260     */
261     virtual GrContext* getGrContext();
262 
263     /** Returns the pixel base address, SkImageInfo, rowBytes, and origin if the pixels
264         can be read directly. The returned address is only valid
265         while SkCanvas is in scope and unchanged. Any SkCanvas call or SkSurface call
266         may invalidate the returned address and other returned values.
267 
268         If pixels are inaccessible, info, rowBytes, and origin are unchanged.
269 
270         @param info      storage for writable pixels' SkImageInfo; may be nullptr
271         @param rowBytes  storage for writable pixels' row bytes; may be nullptr
272         @param origin    storage for SkCanvas top layer origin, its top-left corner;
273                          may be nullptr
274         @return          address of pixels, or nullptr if inaccessible
275     */
276     void* accessTopLayerPixels(SkImageInfo* info, size_t* rowBytes, SkIPoint* origin = nullptr);
277 
278     /** Returns custom context that tracks the SkMatrix and clip.
279 
280         Use SkRasterHandleAllocator to blend Skia drawing with custom drawing, typically performed
281         by the host platform user interface. The custom context returned is generated by
282         SkRasterHandleAllocator::MakeCanvas, which creates a custom canvas with raster storage for
283         the drawing destination.
284 
285         @return  context of custom allocation
286     */
287     SkRasterHandleAllocator::Handle accessTopRasterHandle() const;
288 
289     /** Returns true if SkCanvas has direct access to its pixels.
290 
291         Pixels are readable when SkBaseDevice is raster. Pixels are not readable when SkCanvas
292         is returned from GPU surface, returned by SkDocument::beginPage, returned by
293         SkPictureRecorder::beginRecording, or SkCanvas is the base of a utility class
294         like SkDumpCanvas.
295 
296         pixmap is valid only while SkCanvas is in scope and unchanged. Any
297         SkCanvas or SkSurface call may invalidate the pixmap values.
298 
299         @param pixmap  storage for pixel state if pixels are readable; otherwise, ignored
300         @return        true if SkCanvas has direct access to pixels
301     */
302     bool peekPixels(SkPixmap* pixmap);
303 
304     /** Copies SkRect of pixels from SkCanvas into dstPixels. SkMatrix and clip are
305         ignored.
306 
307         Source SkRect corners are (srcX, srcY) and (imageInfo().width(), imageInfo().height()).
308         Destination SkRect corners are (0, 0) and (dstInfo.width(), dstInfo.height()).
309         Copies each readable pixel intersecting both rectangles, without scaling,
310         converting to dstInfo.colorType() and dstInfo.alphaType() if required.
311 
312         Pixels are readable when SkBaseDevice is raster, or backed by a GPU.
313         Pixels are not readable when SkCanvas is returned by SkDocument::beginPage,
314         returned by SkPictureRecorder::beginRecording, or SkCanvas is the base of a utility
315         class like SkDumpCanvas.
316 
317         The destination pixel storage must be allocated by the caller.
318 
319         Pixel values are converted only if SkColorType and SkAlphaType
320         do not match. Only pixels within both source and destination rectangles
321         are copied. dstPixels contents outside SkRect intersection are unchanged.
322 
323         Pass negative values for srcX or srcY to offset pixels across or down destination.
324 
325         Does not copy, and returns false if:
326         - Source and destination rectangles do not intersect.
327         - SkCanvas pixels could not be converted to dstInfo.colorType() or dstInfo.alphaType().
328         - SkCanvas pixels are not readable; for instance, SkCanvas is document-based.
329         - dstRowBytes is too small to contain one row of pixels.
330 
331         @param dstInfo      width, height, SkColorType, and SkAlphaType of dstPixels
332         @param dstPixels    storage for pixels; dstInfo.height() times dstRowBytes, or larger
333         @param dstRowBytes  size of one destination row; dstInfo.width() times pixel size, or larger
334         @param srcX         offset into readable pixels in x; may be negative
335         @param srcY         offset into readable pixels in y; may be negative
336         @return             true if pixels were copied
337     */
338     bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
339                     int srcX, int srcY);
340 
341     /** Copies SkRect of pixels from SkCanvas into pixmap. SkMatrix and clip are
342         ignored.
343 
344         Source SkRect corners are (srcX, srcY) and (imageInfo().width(), imageInfo().height()).
345         Destination SkRect corners are (0, 0) and (pixmap.width(), pixmap.height()).
346         Copies each readable pixel intersecting both rectangles, without scaling,
347         converting to pixmap.colorType() and pixmap.alphaType() if required.
348 
349         Pixels are readable when SkBaseDevice is raster, or backed by a GPU.
350         Pixels are not readable when SkCanvas is returned by SkDocument::beginPage,
351         returned by SkPictureRecorder::beginRecording, or SkCanvas is the base of a utility
352         class like SkDumpCanvas.
353 
354         Caller must allocate pixel storage in pixmap if needed.
355 
356         Pixel values are converted only if SkColorType and SkAlphaType
357         do not match. Only pixels within both source and destination SkRect
358         are copied. pixmap pixels contents outside SkRect intersection are unchanged.
359 
360         Pass negative values for srcX or srcY to offset pixels across or down pixmap.
361 
362         Does not copy, and returns false if:
363         - Source and destination rectangles do not intersect.
364         - SkCanvas pixels could not be converted to pixmap.colorType() or pixmap.alphaType().
365         - SkCanvas pixels are not readable; for instance, SkCanvas is document-based.
366         - SkPixmap pixels could not be allocated.
367         - pixmap.rowBytes() is too small to contain one row of pixels.
368 
369         @param pixmap  storage for pixels copied from SkCanvas
370         @param srcX    offset into readable pixels in x; may be negative
371         @param srcY    offset into readable pixels in y; may be negative
372         @return        true if pixels were copied
373     */
374     bool readPixels(const SkPixmap& pixmap, int srcX, int srcY);
375 
376     /** Copies SkRect of pixels from SkCanvas into bitmap. SkMatrix and clip are
377         ignored.
378 
379         Source SkRect corners are (srcX, srcY) and (imageInfo().width(), imageInfo().height()).
380         Destination SkRect corners are (0, 0) and (bitmap.width(), bitmap.height()).
381         Copies each readable pixel intersecting both rectangles, without scaling,
382         converting to bitmap.colorType() and bitmap.alphaType() if required.
383 
384         Pixels are readable when SkBaseDevice is raster, or backed by a GPU.
385         Pixels are not readable when SkCanvas is returned by SkDocument::beginPage,
386         returned by SkPictureRecorder::beginRecording, or SkCanvas is the base of a utility
387         class like SkDumpCanvas.
388 
389         Caller must allocate pixel storage in bitmap if needed.
390 
391         SkBitmap values are converted only if SkColorType and SkAlphaType
392         do not match. Only pixels within both source and destination rectangles
393         are copied. SkBitmap pixels outside SkRect intersection are unchanged.
394 
395         Pass negative values for srcX or srcY to offset pixels across or down bitmap.
396 
397         Does not copy, and returns false if:
398         - Source and destination rectangles do not intersect.
399         - SkCanvas pixels could not be converted to bitmap.colorType() or bitmap.alphaType().
400         - SkCanvas pixels are not readable; for instance, SkCanvas is document-based.
401         - bitmap pixels could not be allocated.
402         - bitmap.rowBytes() is too small to contain one row of pixels.
403 
404         @param bitmap  storage for pixels copied from SkCanvas
405         @param srcX    offset into readable pixels in x; may be negative
406         @param srcY    offset into readable pixels in y; may be negative
407         @return        true if pixels were copied
408     */
409     bool readPixels(const SkBitmap& bitmap, int srcX, int srcY);
410 
411     /** Copies SkRect from pixels to SkCanvas. SkMatrix and clip are ignored.
412         Source SkRect corners are (0, 0) and (info.width(), info.height()).
413         Destination SkRect corners are (x, y) and
414         (imageInfo().width(), imageInfo().height()).
415 
416         Copies each readable pixel intersecting both rectangles, without scaling,
417         converting to imageInfo().colorType() and imageInfo().alphaType() if required.
418 
419         Pixels are writable when SkBaseDevice is raster, or backed by a GPU.
420         Pixels are not writable when SkCanvas is returned by SkDocument::beginPage,
421         returned by SkPictureRecorder::beginRecording, or SkCanvas is the base of a utility
422         class like SkDumpCanvas.
423 
424         Pixel values are converted only if SkColorType and SkAlphaType
425         do not match. Only pixels within both source and destination rectangles
426         are copied. SkCanvas pixels outside SkRect intersection are unchanged.
427 
428         Pass negative values for x or y to offset pixels to the left or
429         above SkCanvas pixels.
430 
431         Does not copy, and returns false if:
432         - Source and destination rectangles do not intersect.
433         - pixels could not be converted to SkCanvas imageInfo().colorType() or
434         imageInfo().alphaType().
435         - SkCanvas pixels are not writable; for instance, SkCanvas is document-based.
436         - rowBytes is too small to contain one row of pixels.
437 
438         @param info      width, height, SkColorType, and SkAlphaType of pixels
439         @param pixels    pixels to copy, of size info.height() times rowBytes, or larger
440         @param rowBytes  size of one row of pixels; info.width() times pixel size, or larger
441         @param x         offset into SkCanvas writable pixels in x; may be negative
442         @param y         offset into SkCanvas writable pixels in y; may be negative
443         @return          true if pixels were written to SkCanvas
444     */
445     bool writePixels(const SkImageInfo& info, const void* pixels, size_t rowBytes, int x, int y);
446 
447     /** Copies SkRect from pixels to SkCanvas. SkMatrix and clip are ignored.
448         Source SkRect corners are (0, 0) and (bitmap.width(), bitmap.height()).
449 
450         Destination SkRect corners are (x, y) and
451         (imageInfo().width(), imageInfo().height()).
452 
453         Copies each readable pixel intersecting both rectangles, without scaling,
454         converting to imageInfo().colorType() and imageInfo().alphaType() if required.
455 
456         Pixels are writable when SkBaseDevice is raster, or backed by a GPU.
457         Pixels are not writable when SkCanvas is returned by SkDocument::beginPage,
458         returned by SkPictureRecorder::beginRecording, or SkCanvas is the base of a utility
459         class like SkDumpCanvas.
460 
461         Pixel values are converted only if SkColorType and SkAlphaType
462         do not match. Only pixels within both source and destination rectangles
463         are copied. SkCanvas pixels outside SkRect intersection are unchanged.
464 
465         Pass negative values for x or y to offset pixels to the left or
466         above SkCanvas pixels.
467 
468         Does not copy, and returns false if:
469         - Source and destination rectangles do not intersect.
470         - bitmap does not have allocated pixels.
471         - bitmap pixels could not be converted to SkCanvas imageInfo().colorType() or
472         imageInfo().alphaType().
473         - SkCanvas pixels are not writable; for instance, SkCanvas is document based.
474         - bitmap pixels are inaccessible; for instance, bitmap wraps a texture.
475 
476         @param bitmap  contains pixels copied to SkCanvas
477         @param x       offset into SkCanvas writable pixels in x; may be negative
478         @param y       offset into SkCanvas writable pixels in y; may be negative
479         @return        true if pixels were written to SkCanvas
480     */
481     bool writePixels(const SkBitmap& bitmap, int x, int y);
482 
483     /** Saves SkMatrix, clip, and SkDrawFilter (SkDrawFilter deprecated on most platforms).
484         Calling restore() discards changes to SkMatrix, clip, and SkDrawFilter,
485         restoring the SkMatrix, clip, and SkDrawFilter to their state when save() was called.
486 
487         SkMatrix may be changed by translate(), scale(), rotate(), skew(), concat(), setMatrix(),
488         and resetMatrix(). Clip may be changed by clipRect(), clipRRect(), clipPath(), clipRegion().
489 
490         Saved SkCanvas state is put on a stack; multiple calls to save() should be balance
491         by an equal number of calls to restore().
492 
493         Call restoreToCount() with result to restore this and subsequent saves.
494 
495         @return  depth of saved stack
496     */
497     int save();
498 
499     /** Saves SkMatrix, clip, and SkDrawFilter (SkDrawFilter deprecated on most platforms),
500         and allocates a SkBitmap for subsequent drawing.
501         Calling restore() discards changes to SkMatrix, clip, and SkDrawFilter,
502         and draws the SkBitmap.
503 
504         SkMatrix may be changed by translate(), scale(), rotate(), skew(), concat(),
505         setMatrix(), and resetMatrix(). Clip may be changed by clipRect(), clipRRect(),
506         clipPath(), clipRegion().
507 
508         SkRect bounds suggests but does not define the SkBitmap size. To clip drawing to
509         a specific rectangle, use clipRect().
510 
511         Optional SkPaint paint applies color alpha, SkColorFilter, SkImageFilter, and
512         SkBlendMode when restore() is called.
513 
514         Call restoreToCount() with returned value to restore this and subsequent saves.
515 
516         @param bounds  hint to limit the size of the layer; may be nullptr
517         @param paint   graphics state for layer; may be nullptr
518         @return        depth of saved stack
519     */
520     int saveLayer(const SkRect* bounds, const SkPaint* paint);
521 
522     /** Saves SkMatrix, clip, and SkDrawFilter (SkDrawFilter deprecated on most platforms),
523         and allocates a SkBitmap for subsequent drawing.
524         Calling restore() discards changes to SkMatrix, clip, and SkDrawFilter,
525         and draws the SkBitmap.
526 
527         SkMatrix may be changed by translate(), scale(), rotate(), skew(), concat(),
528         setMatrix(), and resetMatrix(). Clip may be changed by clipRect(), clipRRect(),
529         clipPath(), clipRegion().
530 
531         SkRect bounds suggests but does not define the layer size. To clip drawing to
532         a specific rectangle, use clipRect().
533 
534         Optional SkPaint paint applies color alpha, SkColorFilter, SkImageFilter, and
535         SkBlendMode when restore() is called.
536 
537         Call restoreToCount() with returned value to restore this and subsequent saves.
538 
539         @param bounds  hint to limit the size of layer; may be nullptr
540         @param paint   graphics state for layer; may be nullptr
541         @return        depth of saved stack
542     */
saveLayer(const SkRect & bounds,const SkPaint * paint)543     int saveLayer(const SkRect& bounds, const SkPaint* paint) {
544         return this->saveLayer(&bounds, paint);
545     }
546 
547     /** Saves SkMatrix, clip, and SkDrawFilter (SkDrawFilter deprecated on most platforms),
548         and allocates a SkBitmap for subsequent drawing.
549         LCD text is preserved when the layer is drawn to the prior layer.
550 
551         Calling restore() discards changes to SkMatrix, clip, and SkDrawFilter,
552         and draws layer.
553 
554         SkMatrix may be changed by translate(), scale(), rotate(), skew(), concat(),
555         setMatrix(), and resetMatrix(). Clip may be changed by clipRect(), clipRRect(),
556         clipPath(), clipRegion().
557 
558         SkRect bounds suggests but does not define the layer size. To clip drawing to
559         a specific rectangle, use clipRect().
560 
561         Optional SkPaint paint applies color alpha, SkColorFilter, SkImageFilter, and
562         SkBlendMode when restore() is called.
563 
564         Call restoreToCount() with returned value to restore this and subsequent saves.
565 
566         Draw text on an opaque background so that LCD text blends correctly with the
567         prior layer. LCD text drawn on a background with transparency may result in
568         incorrect blending.
569 
570         @param bounds  hint to limit the size of layer; may be nullptr
571         @param paint   graphics state for layer; may be nullptr
572         @return        depth of saved stack
573     */
574     int saveLayerPreserveLCDTextRequests(const SkRect* bounds, const SkPaint* paint);
575 
576     /** Saves SkMatrix, clip, and SkDrawFilter (SkDrawFilter deprecated on most platforms),
577         and allocates SkBitmap for subsequent drawing.
578 
579         Calling restore() discards changes to SkMatrix, clip, and SkDrawFilter,
580         and blends layer with alpha opacity onto prior layer.
581 
582         SkMatrix may be changed by translate(), scale(), rotate(), skew(), concat(),
583         setMatrix(), and resetMatrix(). Clip may be changed by clipRect(), clipRRect(),
584         clipPath(), clipRegion().
585 
586         SkRect bounds suggests but does not define layer size. To clip drawing to
587         a specific rectangle, use clipRect().
588 
589         alpha of zero is fully transparent, 255 is fully opaque.
590 
591         Call restoreToCount() with returned value to restore this and subsequent saves.
592 
593         @param bounds  hint to limit the size of layer; may be nullptr
594         @param alpha   opacity of layer
595         @return        depth of saved stack
596     */
597     int saveLayerAlpha(const SkRect* bounds, U8CPU alpha);
598 
599     /** \enum
600         SaveLayerFlags provides options that may be used in any combination in SaveLayerRec,
601         defining how layer allocated by saveLayer() operates.
602     */
603     enum {
604         /** Creates layer for LCD text. Flag is ignored if layer SkPaint contains
605             SkImageFilter or SkColorFilter.
606         */
607         kPreserveLCDText_SaveLayerFlag        = 1 << 1,
608 
609         /** Initializes layer with the contents of the previous layer. */
610         kInitWithPrevious_SaveLayerFlag       = 1 << 2,
611 
612 #ifdef SK_SUPPORT_LEGACY_CLIPTOLAYERFLAG
613         /** To be deprecated soon. */
614         kDontClipToLayer_Legacy_SaveLayerFlag = kDontClipToLayer_PrivateSaveLayerFlag,
615 #endif
616     };
617 
618     typedef uint32_t SaveLayerFlags;
619 
620     /** \struct SkCanvas::SaveLayerRec
621         SaveLayerRec contains the state used to create the layer.
622     */
623     struct SaveLayerRec {
624 
625         /** Sets fBounds, fPaint, and fBackdrop to nullptr. Clears fSaveLayerFlags.
626 
627             @return  empty SaveLayerRec
628         */
SaveLayerRecSaveLayerRec629         SaveLayerRec() {}
630 
631         /** Sets fBounds, fPaint, and fSaveLayerFlags; sets fBackdrop to nullptr.
632 
633             @param bounds          layer dimensions; may be nullptr
634             @param paint           applied to layer when overlaying prior layer; may be nullptr
635             @param saveLayerFlags  SaveLayerRec options to modify layer
636             @return                SaveLayerRec with empty backdrop
637         */
638         SaveLayerRec(const SkRect* bounds, const SkPaint* paint, SaveLayerFlags saveLayerFlags = 0)
fBoundsSaveLayerRec639             : fBounds(bounds)
640             , fPaint(paint)
641             , fSaveLayerFlags(saveLayerFlags)
642         {}
643 
644         /** Sets fBounds, fPaint, fBackdrop, and fSaveLayerFlags.
645 
646             @param bounds          layer dimensions; may be nullptr
647             @param paint           applied to layer when overlaying prior layer;
648                                    may be nullptr
649             @param backdrop        prior layer copied with SkImageFilter; may be nullptr
650             @param saveLayerFlags  SaveLayerRec options to modify layer
651             @return                SaveLayerRec fully specified
652         */
SaveLayerRecSaveLayerRec653         SaveLayerRec(const SkRect* bounds, const SkPaint* paint, const SkImageFilter* backdrop,
654                      SaveLayerFlags saveLayerFlags)
655             : fBounds(bounds)
656             , fPaint(paint)
657             , fBackdrop(backdrop)
658             , fSaveLayerFlags(saveLayerFlags)
659         {}
660 
661         /** EXPERIMENTAL: Not ready for general use.
662             Sets fBounds, fPaint, fBackdrop, fClipMask, fClipMatrix, and fSaveLayerFlags.
663             clipMatrix uses color alpha channel of image, transformed by clipMatrix, to clip
664             layer when drawn to SkCanvas.
665 
666             Implementation is not complete; has no effect if SkBaseDevice is GPU-backed.
667 
668             @param bounds          layer dimensions; may be nullptr
669             @param paint           graphics state applied to layer when overlaying prior
670                                    layer; may be nullptr
671             @param backdrop        prior layer copied with SkImageFilter;
672                                    may be nullptr
673             @param clipMask        clip applied to layer; may be nullptr
674             @param clipMatrix      matrix applied to clipMask; may be nullptr to use
675                                    identity matrix
676             @param saveLayerFlags  SaveLayerRec options to modify layer
677             @return                SaveLayerRec fully specified
678         */
SaveLayerRecSaveLayerRec679         SaveLayerRec(const SkRect* bounds, const SkPaint* paint, const SkImageFilter* backdrop,
680                      const SkImage* clipMask, const SkMatrix* clipMatrix,
681                      SaveLayerFlags saveLayerFlags)
682             : fBounds(bounds)
683             , fPaint(paint)
684             , fBackdrop(backdrop)
685             , fClipMask(clipMask)
686             , fClipMatrix(clipMatrix)
687             , fSaveLayerFlags(saveLayerFlags)
688         {}
689 
690         /** fBounds is used as a hint to limit the size of layer; may be nullptr.
691             fBounds suggests but does not define layer size. To clip drawing to
692             a specific rectangle, use clipRect().
693         */
694         const SkRect*        fBounds         = nullptr;
695 
696         /** fPaint modifies how layer overlays the prior layer; may be nullptr.
697             color alpha, SkBlendMode, SkColorFilter, SkDrawLooper, SkImageFilter, and
698             SkMaskFilter affect layer draw.
699         */
700         const SkPaint*       fPaint          = nullptr;
701 
702         /** fBackdrop applies SkImageFilter to the prior layer when copying to the layer;
703             may be nullptr. Use kInitWithPrevious_SaveLayerFlag to copy the
704             prior layer without an SkImageFilter.
705         */
706         const SkImageFilter* fBackdrop       = nullptr;
707 
708         /** restore() clips layer by the color alpha channel of fClipMask when
709             layer is copied to SkBaseDevice. fClipMask may be nullptr.    .
710         */
711         const SkImage*       fClipMask       = nullptr;
712 
713         /** fClipMatrix transforms fClipMask before it clips layer. If
714             fClipMask describes a translucent gradient, it may be scaled and rotated
715             without introducing artifacts. fClipMatrix may be nullptr.
716         */
717         const SkMatrix*      fClipMatrix     = nullptr;
718 
719         /** fSaveLayerFlags are used to create layer without transparency,
720             create layer for LCD text, and to create layer with the
721             contents of the previous layer.
722         */
723         SaveLayerFlags       fSaveLayerFlags = 0;
724 
725     };
726 
727     /** Saves SkMatrix, clip, and SkDrawFilter (SkDrawFilter deprecated on most platforms),
728         and allocates SkBitmap for subsequent drawing.
729 
730         Calling restore() discards changes to SkMatrix, clip, and SkDrawFilter,
731         and blends SkBitmap with color alpha opacity onto the prior layer.
732 
733         SkMatrix may be changed by translate(), scale(), rotate(), skew(), concat(),
734         setMatrix(), and resetMatrix(). Clip may be changed by clipRect(), clipRRect(),
735         clipPath(), clipRegion().
736 
737         SaveLayerRec contains the state used to create the layer.
738 
739         Call restoreToCount() with returned value to restore this and subsequent saves.
740 
741         @param layerRec  layer state
742         @return          depth of save state stack
743     */
744     int saveLayer(const SaveLayerRec& layerRec);
745 
746     /** Removes changes to SkMatrix, clip, and SkDrawFilter since SkCanvas state was
747         last saved. The state is removed from the stack.
748 
749         Does nothing if the stack is empty.
750     */
751     void restore();
752 
753     /** Returns the number of saved states, each containing: SkMatrix, clip, and SkDrawFilter.
754         Equals the number of save() calls less the number of restore() calls plus one.
755         The save count of a new canvas is one.
756 
757         @return  depth of save state stack
758     */
759     int getSaveCount() const;
760 
761     /** Restores state to SkMatrix, clip, and SkDrawFilter values when save(), saveLayer(),
762         saveLayerPreserveLCDTextRequests(), or saveLayerAlpha() returned saveCount.
763 
764         Does nothing if saveCount is greater than state stack count.
765         Restores state to initial values if saveCount is less than or equal to one.
766 
767         @param saveCount  depth of state stack to restore
768     */
769     void restoreToCount(int saveCount);
770 
771     /** Translate SkMatrix by dx along the x-axis and dy along the y-axis.
772 
773         Mathematically, replace SkMatrix with a translation matrix
774         premultiplied with SkMatrix.
775 
776         This has the effect of moving the drawing by (dx, dy) before transforming
777         the result with SkMatrix.
778 
779         @param dx  distance to translate in x
780         @param dy  distance to translate in y
781     */
782     void translate(SkScalar dx, SkScalar dy);
783 
784     /** Scale SkMatrix by sx on the x-axis and sy on the y-axis.
785 
786         Mathematically, replace SkMatrix with a scale matrix
787         premultiplied with SkMatrix.
788 
789         This has the effect of scaling the drawing by (sx, sy) before transforming
790         the result with SkMatrix.
791 
792         @param sx  amount to scale in x
793         @param sy  amount to scale in y
794     */
795     void scale(SkScalar sx, SkScalar sy);
796 
797     /** Rotate SkMatrix by degrees. Positive degrees rotates clockwise.
798 
799         Mathematically, replace SkMatrix with a rotation matrix
800         premultiplied with SkMatrix.
801 
802         This has the effect of rotating the drawing by degrees before transforming
803         the result with SkMatrix.
804 
805         @param degrees  amount to rotate, in degrees
806     */
807     void rotate(SkScalar degrees);
808 
809     /** Rotate SkMatrix by degrees about a point at (px, py). Positive degrees rotates
810         clockwise.
811 
812         Mathematically, construct a rotation matrix. Premultiply the rotation matrix by
813         a translation matrix, then replace SkMatrix with the resulting matrix
814         premultiplied with SkMatrix.
815 
816         This has the effect of rotating the drawing about a given point before
817         transforming the result with SkMatrix.
818 
819         @param degrees  amount to rotate, in degrees
820         @param px       x-coordinate of the point to rotate about
821         @param py       y-coordinate of the point to rotate about
822     */
823     void rotate(SkScalar degrees, SkScalar px, SkScalar py);
824 
825     /** Skew SkMatrix by sx on the x-axis and sy on the y-axis. A positive value of sx
826         skews the drawing right as y increases; a positive value of sy skews the drawing
827         down as x increases.
828 
829         Mathematically, replace SkMatrix with a skew matrix premultiplied with SkMatrix.
830 
831         This has the effect of skewing the drawing by (sx, sy) before transforming
832         the result with SkMatrix.
833 
834         @param sx  amount to skew in x
835         @param sy  amount to skew in y
836     */
837     void skew(SkScalar sx, SkScalar sy);
838 
839     /** Replace SkMatrix with matrix premultiplied with existing SkMatrix.
840 
841         This has the effect of transforming the drawn geometry by matrix, before
842         transforming the result with existing SkMatrix.
843 
844         @param matrix  matrix to premultiply with existing SkMatrix
845     */
846     void concat(const SkMatrix& matrix);
847 
848     /** Replace SkMatrix with matrix.
849         Unlike concat(), any prior matrix state is overwritten.
850 
851         @param matrix  matrix to copy, replacing existing SkMatrix
852     */
853     void setMatrix(const SkMatrix& matrix);
854 
855     /** Sets SkMatrix to the identity matrix.
856         Any prior matrix state is overwritten.
857     */
858     void resetMatrix();
859 
860     /** Replace clip with the intersection or difference of clip and rect,
861         with an aliased or anti-aliased clip edge. rect is transformed by SkMatrix
862         before it is combined with clip.
863 
864         @param rect         SkRect to combine with clip
865         @param op           SkClipOp to apply to clip
866         @param doAntiAlias  true if clip is to be anti-aliased
867     */
868     void clipRect(const SkRect& rect, SkClipOp op, bool doAntiAlias);
869 
870     /** Replace clip with the intersection or difference of clip and rect.
871         Resulting clip is aliased; pixels are fully contained by the clip.
872         rect is transformed by SkMatrix before it is combined with clip.
873 
874         @param rect  SkRect to combine with clip
875         @param op    SkClipOp to apply to clip
876     */
clipRect(const SkRect & rect,SkClipOp op)877     void clipRect(const SkRect& rect, SkClipOp op) {
878         this->clipRect(rect, op, false);
879     }
880 
881     /** Replace clip with the intersection of clip and rect.
882         Resulting clip is aliased; pixels are fully contained by the clip.
883         rect is transformed by SkMatrix
884         before it is combined with clip.
885 
886         @param rect         SkRect to combine with clip
887         @param doAntiAlias  true if clip is to be anti-aliased
888     */
889     void clipRect(const SkRect& rect, bool doAntiAlias = false) {
890         this->clipRect(rect, SkClipOp::kIntersect, doAntiAlias);
891     }
892 
893     /** Sets the maximum clip rectangle, which can be set by clipRect(), clipRRect() and
894         clipPath() and intersect the current clip with the specified rect.
895         The maximum clip affects only future clipping operations; it is not retroactive.
896         The clip restriction is not recorded in pictures.
897 
898         Pass an empty rect to disable maximum clip.
899         This is private API to be used only by Android framework.
900 
901         @param rect  maximum allowed clip in device coordinates
902     */
903     void androidFramework_setDeviceClipRestriction(const SkIRect& rect);
904 
905     /** Replace clip with the intersection or difference of clip and rrect,
906         with an aliased or anti-aliased clip edge.
907         rrect is transformed by SkMatrix
908         before it is combined with clip.
909 
910         @param rrect        SkRRect to combine with clip
911         @param op           SkClipOp to apply to clip
912         @param doAntiAlias  true if clip is to be anti-aliased
913     */
914     void clipRRect(const SkRRect& rrect, SkClipOp op, bool doAntiAlias);
915 
916     /** Replace clip with the intersection or difference of clip and rrect.
917         Resulting clip is aliased; pixels are fully contained by the clip.
918         rrect is transformed by SkMatrix before it is combined with clip.
919 
920         @param rrect  SkRRect to combine with clip
921         @param op     SkClipOp to apply to clip
922     */
clipRRect(const SkRRect & rrect,SkClipOp op)923     void clipRRect(const SkRRect& rrect, SkClipOp op) {
924         this->clipRRect(rrect, op, false);
925     }
926 
927     /** Replace clip with the intersection of clip and rrect,
928         with an aliased or anti-aliased clip edge.
929         rrect is transformed by SkMatrix before it is combined with clip.
930 
931         @param rrect        SkRRect to combine with clip
932         @param doAntiAlias  true if clip is to be anti-aliased
933     */
934     void clipRRect(const SkRRect& rrect, bool doAntiAlias = false) {
935         this->clipRRect(rrect, SkClipOp::kIntersect, doAntiAlias);
936     }
937 
938     /** Replace clip with the intersection or difference of clip and path,
939         with an aliased or anti-aliased clip edge. SkPath::FillType determines if path
940         describes the area inside or outside its contours; and if path contour overlaps
941         itself or another path contour, whether the overlaps form part of the area.
942         path is transformed by SkMatrix before it is combined with clip.
943 
944         @param path         SkPath to combine with clip
945         @param op           SkClipOp to apply to clip
946         @param doAntiAlias  true if clip is to be anti-aliased
947     */
948     void clipPath(const SkPath& path, SkClipOp op, bool doAntiAlias);
949 
950     /** Replace clip with the intersection or difference of clip and path.
951         Resulting clip is aliased; pixels are fully contained by the clip.
952         SkPath::FillType determines if path
953         describes the area inside or outside its contours; and if path contour overlaps
954         itself or another path contour, whether the overlaps form part of the area.
955         path is transformed by SkMatrix
956         before it is combined with clip.
957 
958         @param path  SkPath to combine with clip
959         @param op    SkClipOp to apply to clip
960     */
clipPath(const SkPath & path,SkClipOp op)961     void clipPath(const SkPath& path, SkClipOp op) {
962         this->clipPath(path, op, false);
963     }
964 
965     /** Replace clip with the intersection of clip and path.
966         Resulting clip is aliased; pixels are fully contained by the clip.
967         SkPath::FillType determines if path
968         describes the area inside or outside its contours; and if path contour overlaps
969         itself or another path contour, whether the overlaps form part of the area.
970         path is transformed by SkMatrix before it is combined with clip.
971 
972         @param path         SkPath to combine with clip
973         @param doAntiAlias  true if clip is to be anti-aliased
974     */
975     void clipPath(const SkPath& path, bool doAntiAlias = false) {
976         this->clipPath(path, SkClipOp::kIntersect, doAntiAlias);
977     }
978 
979     /** EXPERIMENTAL: Only used for testing.
980         Set to simplify clip stack using PathOps.
981     */
setAllowSimplifyClip(bool allow)982     void setAllowSimplifyClip(bool allow) {
983         fAllowSimplifyClip = allow;
984     }
985 
986     /** Replace clip with the intersection or difference of clip and SkRegion deviceRgn.
987         Resulting clip is aliased; pixels are fully contained by the clip.
988         deviceRgn is unaffected by SkMatrix.
989 
990         @param deviceRgn  SkRegion to combine with clip
991         @param op         SkClipOp to apply to clip
992     */
993     void clipRegion(const SkRegion& deviceRgn, SkClipOp op = SkClipOp::kIntersect);
994 
995     /** Return true if SkRect rect, transformed by SkMatrix, can be quickly determined to be
996         outside of clip. May return false even though rect is outside of clip.
997 
998         Use to check if an area to be drawn is clipped out, to skip subsequent draw calls.
999 
1000         @param rect  SkRect to compare with clip
1001         @return      true if rect, transformed by SkMatrix, does not intersect clip
1002     */
1003     bool quickReject(const SkRect& rect) const;
1004 
1005     /** Return true if path, transformed by SkMatrix, can be quickly determined to be
1006         outside of clip. May return false even though path is outside of clip.
1007 
1008         Use to check if an area to be drawn is clipped out, to skip subsequent draw calls.
1009 
1010         @param path  SkPath to compare with clip
1011         @return      true if path, transformed by SkMatrix, does not intersect clip
1012     */
1013     bool quickReject(const SkPath& path) const;
1014 
1015     /** Return bounds of clip, transformed by inverse of SkMatrix. If clip is empty,
1016         return SkRect::MakeEmpty, where all SkRect sides equal zero.
1017 
1018         SkRect returned is outset by one to account for partial pixel coverage if clip
1019         is anti-aliased.
1020 
1021         @return  bounds of clip in local coordinates
1022     */
1023     SkRect getLocalClipBounds() const;
1024 
1025     /** Return bounds of clip, transformed by inverse of SkMatrix. If clip is empty,
1026         return false, and set bounds to SkRect::MakeEmpty, where all SkRect sides equal zero.
1027 
1028         bounds is outset by one to account for partial pixel coverage if clip
1029         is anti-aliased.
1030 
1031         @param bounds  SkRect of clip in local coordinates
1032         @return        true if clip bounds is not empty
1033     */
getLocalClipBounds(SkRect * bounds)1034     bool getLocalClipBounds(SkRect* bounds) const {
1035         *bounds = this->getLocalClipBounds();
1036         return !bounds->isEmpty();
1037     }
1038 
1039     /** Return SkIRect bounds of clip, unaffected by SkMatrix. If clip is empty,
1040         return SkRect::MakeEmpty, where all SkRect sides equal zero.
1041 
1042         Unlike getLocalClipBounds(), returned SkIRect is not outset.
1043 
1044         @return  bounds of clip in SkBaseDevice coordinates
1045     */
1046     SkIRect getDeviceClipBounds() const;
1047 
1048     /** Return SkIRect bounds of clip, unaffected by SkMatrix. If clip is empty,
1049         return false, and set bounds to SkRect::MakeEmpty, where all SkRect sides equal zero.
1050 
1051         Unlike getLocalClipBounds(), bounds is not outset.
1052 
1053         @param bounds  SkRect of clip in device coordinates
1054         @return        true if clip bounds is not empty
1055     */
getDeviceClipBounds(SkIRect * bounds)1056     bool getDeviceClipBounds(SkIRect* bounds) const {
1057         *bounds = this->getDeviceClipBounds();
1058         return !bounds->isEmpty();
1059     }
1060 
1061     /** Fill clip with color color.
1062         mode determines how ARGB is combined with destination.
1063 
1064         @param color  unpremultiplied ARGB
1065         @param mode   SkBlendMode used to combine source color and destination
1066     */
1067     void drawColor(SkColor color, SkBlendMode mode = SkBlendMode::kSrcOver);
1068 
1069     /** Fill clip with color color using SkBlendMode::kSrc.
1070         This has the effect of replacing all pixels contained by clip with color.
1071 
1072         @param color  unpremultiplied ARGB
1073     */
clear(SkColor color)1074     void clear(SkColor color) {
1075         this->drawColor(color, SkBlendMode::kSrc);
1076     }
1077 
1078     /** Make SkCanvas contents undefined. Subsequent calls that read SkCanvas pixels,
1079         such as drawing with SkBlendMode, return undefined results. discard() does
1080         not change clip or SkMatrix.
1081 
1082         discard() may do nothing, depending on the implementation of SkSurface or SkBaseDevice
1083         that created SkCanvas.
1084 
1085         discard() allows optimized performance on subsequent draws by removing
1086         cached data associated with SkSurface or SkBaseDevice.
1087         It is not necessary to call discard() once done with SkCanvas;
1088         any cached data is deleted when owning SkSurface or SkBaseDevice is deleted.
1089     */
discard()1090     void discard() { this->onDiscard(); }
1091 
1092     /** Fill clip with SkPaint paint. SkPaint components SkMaskFilter, SkShader,
1093         SkColorFilter, SkImageFilter, and SkBlendMode affect drawing;
1094         SkPathEffect in paint is ignored.
1095 
1096         @param paint  graphics state used to fill SkCanvas
1097     */
1098     void drawPaint(const SkPaint& paint);
1099 
1100     /** \enum SkCanvas::PointMode
1101         Selects if an array of points are drawn as discrete points, as lines, or as
1102         an open polygon.
1103     */
1104     enum PointMode {
1105         kPoints_PointMode,  //!< Draw each point separately.
1106         kLines_PointMode,   //!< Draw each pair of points as a line segment.
1107         kPolygon_PointMode, //!< Draw the array of points as a open polygon.
1108     };
1109 
1110     /** Draw pts using clip, SkMatrix and SkPaint paint.
1111         count is the number of points; if count is less than one, has no effect.
1112         mode may be one of: kPoints_PointMode, kLines_PointMode, or kPolygon_PointMode.
1113 
1114         If mode is kPoints_PointMode, the shape of point drawn depends on paint
1115         SkPaint::Cap. If paint is set to SkPaint::kRound_Cap, each point draws a
1116         circle of diameter SkPaint stroke width. If paint is set to SkPaint::kSquare_Cap
1117         or SkPaint::kButt_Cap, each point draws a square of width and height
1118         SkPaint stroke width.
1119 
1120         If mode is kLines_PointMode, each pair of points draws a line segment.
1121         One line is drawn for every two points; each point is used once. If count is odd,
1122         the final point is ignored.
1123 
1124         If mode is kPolygon_PointMode, each adjacent pair of points draws a line segment.
1125         count minus one lines are drawn; the first and last point are used once.
1126 
1127         Each line segment respects paint SkPaint::Cap and SkPaint stroke width.
1128         SkPaint::Style is ignored, as if were set to SkPaint::kStroke_Style.
1129 
1130         Always draws each element one at a time; is not affected by
1131         SkPaint::Join, and unlike drawPath(), does not create a mask from all points
1132         and lines before drawing.
1133 
1134         @param mode   whether pts draws points or lines
1135         @param count  number of points in the array
1136         @param pts    array of points to draw
1137         @param paint  stroke, blend, color, and so on, used to draw
1138     */
1139     void drawPoints(PointMode mode, size_t count, const SkPoint pts[], const SkPaint& paint);
1140 
1141     /** Draw point at (x, y) using clip, SkMatrix and SkPaint paint.
1142 
1143         The shape of point drawn depends on paint SkPaint::Cap.
1144         If paint is set to SkPaint::kRound_Cap, draw a circle of diameter
1145         SkPaint stroke width. If paint is set to SkPaint::kSquare_Cap or SkPaint::kButt_Cap,
1146         draw a square of width and height SkPaint stroke width.
1147         SkPaint::Style is ignored, as if were set to SkPaint::kStroke_Style.
1148 
1149         @param x      left edge of circle or square
1150         @param y      top edge of circle or square
1151         @param paint  stroke, blend, color, and so on, used to draw
1152     */
1153     void drawPoint(SkScalar x, SkScalar y, const SkPaint& paint);
1154 
1155     /** Draw point p using clip, SkMatrix and SkPaint paint.
1156 
1157         The shape of point drawn depends on paint SkPaint::Cap.
1158         If paint is set to SkPaint::kRound_Cap, draw a circle of diameter
1159         SkPaint stroke width. If paint is set to SkPaint::kSquare_Cap or SkPaint::kButt_Cap,
1160         draw a square of width and height SkPaint stroke width.
1161         SkPaint::Style is ignored, as if were set to SkPaint::kStroke_Style.
1162 
1163         @param p      top-left edge of circle or square
1164         @param paint  stroke, blend, color, and so on, used to draw
1165     */
drawPoint(SkPoint p,const SkPaint & paint)1166     void drawPoint(SkPoint p, const SkPaint& paint) {
1167         this->drawPoint(p.x(), p.y(), paint);
1168     }
1169 
1170     /** Draws line segment from (x0, y0) to (x1, y1) using clip, SkMatrix, and SkPaint paint.
1171         In paint: SkPaint stroke width describes the line thickness;
1172         SkPaint::Cap draws the end rounded or square;
1173         SkPaint::Style is ignored, as if were set to SkPaint::kStroke_Style.
1174 
1175         @param x0     start of line segment on x-axis
1176         @param y0     start of line segment on y-axis
1177         @param x1     end of line segment on x-axis
1178         @param y1     end of line segment on y-axis
1179         @param paint  stroke, blend, color, and so on, used to draw
1180     */
1181     void drawLine(SkScalar x0, SkScalar y0, SkScalar x1, SkScalar y1, const SkPaint& paint);
1182 
1183     /** Draws line segment from p0 to p1 using clip, SkMatrix, and SkPaint paint.
1184         In paint: SkPaint stroke width describes the line thickness;
1185         SkPaint::Cap draws the end rounded or square;
1186         SkPaint::Style is ignored, as if were set to SkPaint::kStroke_Style.
1187 
1188         @param p0     start of line segment
1189         @param p1     end of line segment
1190         @param paint  stroke, blend, color, and so on, used to draw
1191     */
drawLine(SkPoint p0,SkPoint p1,const SkPaint & paint)1192     void drawLine(SkPoint p0, SkPoint p1, const SkPaint& paint) {
1193         this->drawLine(p0.x(), p0.y(), p1.x(), p1.y(), paint);
1194     }
1195 
1196     /** Draw SkRect rect using clip, SkMatrix, and SkPaint paint.
1197         In paint: SkPaint::Style determines if rectangle is stroked or filled;
1198         if stroked, SkPaint stroke width describes the line thickness, and
1199         SkPaint::Join draws the corners rounded or square.
1200 
1201         @param rect   rectangle to draw
1202         @param paint  stroke or fill, blend, color, and so on, used to draw
1203     */
1204     void drawRect(const SkRect& rect, const SkPaint& paint);
1205 
1206     /** Draw SkIRect rect using clip, SkMatrix, and SkPaint paint.
1207         In paint: SkPaint::Style determines if rectangle is stroked or filled;
1208         if stroked, SkPaint stroke width describes the line thickness, and
1209         SkPaint::Join draws the corners rounded or square.
1210 
1211         @param rect   rectangle to draw
1212         @param paint  stroke or fill, blend, color, and so on, used to draw
1213     */
drawIRect(const SkIRect & rect,const SkPaint & paint)1214     void drawIRect(const SkIRect& rect, const SkPaint& paint) {
1215         SkRect r;
1216         r.set(rect);    // promotes the ints to scalars
1217         this->drawRect(r, paint);
1218     }
1219 
1220     /** Draw SkRegion region using clip, SkMatrix, and SkPaint paint.
1221         In paint: SkPaint::Style determines if rectangle is stroked or filled;
1222         if stroked, SkPaint stroke width describes the line thickness, and
1223         SkPaint::Join draws the corners rounded or square.
1224 
1225         @param region  region to draw
1226         @param paint   SkPaint stroke or fill, blend, color, and so on, used to draw
1227     */
1228     void drawRegion(const SkRegion& region, const SkPaint& paint);
1229 
1230     /** Draw oval oval using clip, SkMatrix, and SkPaint.
1231         In paint: SkPaint::Style determines if oval is stroked or filled;
1232         if stroked, SkPaint stroke width describes the line thickness.
1233 
1234         @param oval   SkRect bounds of oval
1235         @param paint  SkPaint stroke or fill, blend, color, and so on, used to draw
1236     */
1237     void drawOval(const SkRect& oval, const SkPaint& paint);
1238 
1239     /** Draw SkRRect rrect using clip, SkMatrix, and SkPaint paint.
1240         In paint: SkPaint::Style determines if rrect is stroked or filled;
1241         if stroked, SkPaint stroke width describes the line thickness.
1242 
1243         rrect may represent a rectangle, circle, oval, uniformly rounded rectangle, or
1244         may have any combination of positive non-square radii for the four corners.
1245 
1246         @param rrect  SkRRect with up to eight corner radii to draw
1247         @param paint  SkPaint stroke or fill, blend, color, and so on, used to draw
1248     */
1249     void drawRRect(const SkRRect& rrect, const SkPaint& paint);
1250 
1251     /** Draw SkRRect outer and inner
1252         using clip, SkMatrix, and SkPaint paint.
1253         outer must contain inner or the drawing is undefined.
1254         In paint: SkPaint::Style determines if SkRRect is stroked or filled;
1255         if stroked, SkPaint stroke width describes the line thickness.
1256         If stroked and SkRRect corner has zero length radii, SkPaint::Join can
1257         draw corners rounded or square.
1258 
1259         GPU-backed platforms optimize drawing when both outer and inner are
1260         concave and outer contains inner. These platforms may not be able to draw
1261         SkPath built with identical data as fast.
1262 
1263         @param outer  SkRRect outer bounds to draw
1264         @param inner  SkRRect inner bounds to draw
1265         @param paint  SkPaint stroke or fill, blend, color, and so on, used to draw
1266     */
1267     void drawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint);
1268 
1269     /** Draw circle at (cx, cy) with radius using clip, SkMatrix, and SkPaint paint.
1270         If radius is zero or less, nothing is drawn.
1271         In paint: SkPaint::Style determines if circle is stroked or filled;
1272         if stroked, SkPaint stroke width describes the line thickness.
1273 
1274         @param cx      circle center on the x-axis
1275         @param cy      circle center on the y-axis
1276         @param radius  half the diameter of circle
1277         @param paint   SkPaint stroke or fill, blend, color, and so on, used to draw
1278     */
1279     void drawCircle(SkScalar cx, SkScalar cy, SkScalar radius, const SkPaint& paint);
1280 
1281     /** Draw circle at center with radius using clip, SkMatrix, and SkPaint paint.
1282         If radius is zero or less, nothing is drawn.
1283         In paint: SkPaint::Style determines if circle is stroked or filled;
1284         if stroked, SkPaint stroke width describes the line thickness.
1285 
1286         @param center  circle center
1287         @param radius  half the diameter of circle
1288         @param paint   SkPaint stroke or fill, blend, color, and so on, used to draw
1289     */
drawCircle(SkPoint center,SkScalar radius,const SkPaint & paint)1290     void drawCircle(SkPoint center, SkScalar radius, const SkPaint& paint) {
1291         this->drawCircle(center.x(), center.y(), radius, paint);
1292     }
1293 
1294     /** Draw arc using clip, SkMatrix, and SkPaint paint.
1295 
1296         Arc is part of oval bounded by oval, sweeping from startAngle to startAngle plus
1297         sweepAngle. startAngle and sweepAngle are in degrees.
1298 
1299         startAngle of zero places start point at the right middle edge of oval.
1300         A positive sweepAngle places arc end point clockwise from start point;
1301         a negative sweepAngle places arc end point counterclockwise from start point.
1302         sweepAngle may exceed 360 degrees, a full circle.
1303         If useCenter is true, draw a wedge that includes lines from oval
1304         center to arc end points. If useCenter is false, draw arc between end points.
1305 
1306         If SkRect oval is empty or sweepAngle is zero, nothing is drawn.
1307 
1308         @param oval        SkRect bounds of oval containing arc to draw
1309         @param startAngle  angle in degrees where arc begins
1310         @param sweepAngle  sweep angle in degrees; positive is clockwise
1311         @param useCenter   if true, include the center of the oval
1312         @param paint       SkPaint stroke or fill, blend, color, and so on, used to draw
1313     */
1314     void drawArc(const SkRect& oval, SkScalar startAngle, SkScalar sweepAngle,
1315                  bool useCenter, const SkPaint& paint);
1316 
1317     /** Draw SkRRect bounded by SkRect rect, with corner radii (rx, ry) using clip,
1318         SkMatrix, and SkPaint paint.
1319 
1320         In paint: SkPaint::Style determines if SkRRect is stroked or filled;
1321         if stroked, SkPaint stroke width describes the line thickness.
1322         If rx or ry are less than zero, they are treated as if they are zero.
1323         If rx plus ry exceeds rect width or rect height, radii are scaled down to fit.
1324         If rx and ry are zero, SkRRect is drawn as SkRect and if stroked is affected by
1325         SkPaint::Join.
1326 
1327         @param rect   SkRect bounds of SkRRect to draw
1328         @param rx     axis length in x of oval describing rounded corners
1329         @param ry     axis length in y of oval describing rounded corners
1330         @param paint  stroke, blend, color, and so on, used to draw
1331     */
1332     void drawRoundRect(const SkRect& rect, SkScalar rx, SkScalar ry, const SkPaint& paint);
1333 
1334     /** Draw SkPath path using clip, SkMatrix, and SkPaint paint.
1335         SkPath contains an array of path contour, each of which may be open or closed.
1336 
1337         In paint: SkPaint::Style determines if SkRRect is stroked or filled:
1338         if filled, SkPath::FillType determines whether path contour describes inside or
1339         outside of fill; if stroked, SkPaint stroke width describes the line thickness,
1340         SkPaint::Cap describes line ends, and SkPaint::Join describes how
1341         corners are drawn.
1342 
1343         @param path   SkPath to draw
1344         @param paint  stroke, blend, color, and so on, used to draw
1345     */
1346     void drawPath(const SkPath& path, const SkPaint& paint);
1347 
1348     /** Draw SkImage image, with its top-left corner at (left, top),
1349         using clip, SkMatrix, and optional SkPaint paint.
1350 
1351         If paint is supplied, apply SkColorFilter, color alpha, SkImageFilter, SkBlendMode,
1352         and SkDrawLooper. If image is kAlpha_8_SkColorType, apply SkShader.
1353         If paint contains SkMaskFilter, generate mask from image bounds. If generated
1354         mask extends beyond image bounds, replicate image edge colors, just as SkShader
1355         made from SkImage::makeShader with SkShader::kClamp_TileMode set replicates the
1356         image edge color when it samples outside of its bounds.
1357 
1358         @param image  uncompressed rectangular map of pixels
1359         @param left   left side of image
1360         @param top    top side of image
1361         @param paint  SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1362                       and so on; or nullptr
1363     */
1364     void drawImage(const SkImage* image, SkScalar left, SkScalar top,
1365                    const SkPaint* paint = nullptr);
1366 
1367     /** Draw SkImage image, with its top-left corner at (left, top),
1368         using clip, SkMatrix, and optional SkPaint paint.
1369 
1370         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1371         SkBlendMode, and SkDrawLooper. If image is kAlpha_8_SkColorType, apply SkShader.
1372         If paint contains SkMaskFilter, generate mask from image bounds. If generated
1373         mask extends beyond image bounds, replicate image edge colors, just as SkShader
1374         made from SkImage::makeShader with SkShader::kClamp_TileMode set replicates the
1375         image edge color when it samples outside of its bounds.
1376 
1377         @param image  uncompressed rectangular map of pixels
1378         @param left   left side of image
1379         @param top    pop side of image
1380         @param paint  SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1381                       and so on; or nullptr
1382     */
1383     void drawImage(const sk_sp<SkImage>& image, SkScalar left, SkScalar top,
1384                    const SkPaint* paint = nullptr) {
1385         this->drawImage(image.get(), left, top, paint);
1386     }
1387 
1388     /** \enum SkCanvas::SrcRectConstraint
1389         SrcRectConstraint controls the behavior at the edge of source SkRect,
1390         provided to drawImageRect(), trading off speed for precision.
1391 
1392         SkImageFilter in SkPaint may sample multiple pixels in the image. Source SkRect
1393         restricts the bounds of pixels that may be read. SkImageFilter may slow down if
1394         it cannot read outside the bounds, when sampling near the edge of source SkRect.
1395         SrcRectConstraint specifies whether an SkImageFilter is allowed to read pixels
1396         outside source SkRect.
1397     */
1398     enum SrcRectConstraint {
1399         /** sampling only inside of its bounds, possibly with a performance penalty. */
1400         kStrict_SrcRectConstraint,
1401 
1402         /** by half the width of SkImageFilter, permitting it to run faster but with
1403             error at the image edges.
1404         */
1405         kFast_SrcRectConstraint,
1406     };
1407 
1408     /** Draw SkRect src of SkImage image, scaled and translated to fill SkRect dst.
1409         Additionally transform draw using clip, SkMatrix, and optional SkPaint paint.
1410 
1411         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1412         SkBlendMode, and SkDrawLooper. If image is kAlpha_8_SkColorType, apply SkShader.
1413         If paint contains SkMaskFilter, generate mask from image bounds.
1414 
1415         If generated mask extends beyond image bounds, replicate image edge colors, just
1416         as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
1417         replicates the image edge color when it samples outside of its bounds.
1418 
1419         constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
1420         sample within src; set to kFast_SrcRectConstraint allows sampling outside to
1421         improve performance.
1422 
1423         @param image       SkImage containing pixels, dimensions, and format
1424         @param src         source SkRect of image to draw from
1425         @param dst         destination SkRect of image to draw to
1426         @param paint       SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1427                            and so on; or nullptr
1428         @param constraint  filter strictly within src or draw faster
1429     */
1430     void drawImageRect(const SkImage* image, const SkRect& src, const SkRect& dst,
1431                        const SkPaint* paint,
1432                        SrcRectConstraint constraint = kStrict_SrcRectConstraint);
1433 
1434     /** Draw SkIRect isrc of SkImage image, scaled and translated to fill SkRect dst.
1435         Note that isrc is on integer pixel boundaries; dst may include fractional
1436         boundaries. Additionally transform draw using clip, SkMatrix, and optional SkPaint
1437         paint.
1438 
1439         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1440         SkBlendMode, and SkDrawLooper. If image is kAlpha_8_SkColorType, apply SkShader.
1441         If paint contains SkMaskFilter, generate mask from image bounds.
1442 
1443         If generated mask extends beyond image bounds, replicate image edge colors, just
1444         as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
1445         replicates the image edge color when it samples outside of its bounds.
1446 
1447         constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
1448         sample within isrc; set to kFast_SrcRectConstraint allows sampling outside to
1449         improve performance.
1450 
1451         @param image       SkImage containing pixels, dimensions, and format
1452         @param isrc        source SkIRect of image to draw from
1453         @param dst         destination SkRect of image to draw to
1454         @param paint       SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1455                            and so on; or nullptr
1456         @param constraint  filter strictly within isrc or draw faster
1457     */
1458     void drawImageRect(const SkImage* image, const SkIRect& isrc, const SkRect& dst,
1459                        const SkPaint* paint,
1460                        SrcRectConstraint constraint = kStrict_SrcRectConstraint);
1461 
1462     /** Draw SkImage image, scaled and translated to fill SkRect dst, using clip, SkMatrix,
1463         and optional SkPaint paint.
1464 
1465         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1466         SkBlendMode, and SkDrawLooper. If image is kAlpha_8_SkColorType, apply SkShader.
1467         If paint contains SkMaskFilter, generate mask from image bounds.
1468 
1469         If generated mask extends beyond image bounds, replicate image edge colors, just
1470         as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
1471         replicates the image edge color when it samples outside of its bounds.
1472 
1473         constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
1474         sample within image; set to kFast_SrcRectConstraint allows sampling outside to
1475         improve performance.
1476 
1477         @param image       SkImage containing pixels, dimensions, and format
1478         @param dst         destination SkRect of image to draw to
1479         @param paint       SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1480                            and so on; or nullptr
1481         @param constraint  filter strictly within image or draw faster
1482     */
1483     void drawImageRect(const SkImage* image, const SkRect& dst, const SkPaint* paint,
1484                        SrcRectConstraint constraint = kStrict_SrcRectConstraint);
1485 
1486     /** Draw SkRect src of SkImage image, scaled and translated to fill SkRect dst.
1487         Additionally transform draw using clip, SkMatrix, and optional SkPaint paint.
1488 
1489         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1490         SkBlendMode, and SkDrawLooper. If image is kAlpha_8_SkColorType, apply SkShader.
1491         If paint contains SkMaskFilter, generate mask from image bounds.
1492 
1493         If generated mask extends beyond image bounds, replicate image edge colors, just
1494         as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
1495         replicates the image edge color when it samples outside of its bounds.
1496 
1497         constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
1498         sample within src; set to kFast_SrcRectConstraint allows sampling outside to
1499         improve performance.
1500 
1501         @param image       SkImage containing pixels, dimensions, and format
1502         @param src         source SkRect of image to draw from
1503         @param dst         destination SkRect of image to draw to
1504         @param paint       SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1505                            and so on; or nullptr
1506         @param constraint  filter strictly within src or draw faster
1507     */
1508     void drawImageRect(const sk_sp<SkImage>& image, const SkRect& src, const SkRect& dst,
1509                        const SkPaint* paint,
1510                        SrcRectConstraint constraint = kStrict_SrcRectConstraint) {
1511         this->drawImageRect(image.get(), src, dst, paint, constraint);
1512     }
1513 
1514     /** Draw SkIRect isrc of SkImage image, scaled and translated to fill SkRect dst.
1515         isrc is on integer pixel boundaries; dst may include fractional boundaries.
1516         Additionally transform draw using clip, SkMatrix, and optional SkPaint paint.
1517 
1518         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1519         SkBlendMode, and SkDrawLooper. If image is kAlpha_8_SkColorType, apply SkShader.
1520         If paint contains SkMaskFilter, generate mask from image bounds.
1521 
1522         If generated mask extends beyond image bounds, replicate image edge colors, just
1523         as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
1524         replicates the image edge color when it samples outside of its bounds.
1525 
1526         constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
1527         sample within image; set to kFast_SrcRectConstraint allows sampling outside to
1528         improve performance.
1529 
1530         @param image       SkImage containing pixels, dimensions, and format
1531         @param isrc        source SkIRect of image to draw from
1532         @param dst         destination SkRect of image to draw to
1533         @param paint       SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1534                            and so on; or nullptr
1535         @param constraint  filter strictly within image or draw faster
1536     */
1537     void drawImageRect(const sk_sp<SkImage>& image, const SkIRect& isrc, const SkRect& dst,
1538                        const SkPaint* paint,
1539                        SrcRectConstraint constraint = kStrict_SrcRectConstraint) {
1540         this->drawImageRect(image.get(), isrc, dst, paint, constraint);
1541     }
1542 
1543     /** Draw SkImage image, scaled and translated to fill SkRect dst,
1544         using clip, SkMatrix, and optional SkPaint paint.
1545 
1546         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1547         SkBlendMode, and SkDrawLooper. If image is kAlpha_8_SkColorType, apply SkShader.
1548         If paint contains SkMaskFilter, generate mask from image bounds.
1549 
1550         If generated mask extends beyond image bounds, replicate image edge colors, just
1551         as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
1552         replicates the image edge color when it samples outside of its bounds.
1553 
1554         constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
1555         sample within image; set to kFast_SrcRectConstraint allows sampling outside to
1556         improve performance.
1557 
1558         @param image       SkImage containing pixels, dimensions, and format
1559         @param dst         destination SkRect of image to draw to
1560         @param paint       SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1561                            and so on; or nullptr
1562         @param constraint  filter strictly within image or draw faster
1563     */
1564     void drawImageRect(const sk_sp<SkImage>& image, const SkRect& dst, const SkPaint* paint,
1565                        SrcRectConstraint constraint = kStrict_SrcRectConstraint) {
1566         this->drawImageRect(image.get(), dst, paint, constraint);
1567     }
1568 
1569     /** Draw SkImage image stretched proportionally to fit into SkRect dst.
1570         SkIRect center divides the image into nine sections: four sides, four corners, and
1571         the center. Corners are unmodified or scaled down proportionately if their sides
1572         are larger than dst; center and four sides are scaled to fit remaining space, if any.
1573 
1574         Additionally transform draw using clip, SkMatrix, and optional SkPaint paint.
1575 
1576         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1577         SkBlendMode, and SkDrawLooper. If image is kAlpha_8_SkColorType, apply SkShader.
1578         If paint contains SkMaskFilter, generate mask from image bounds.
1579 
1580         If generated mask extends beyond image bounds, replicate image edge colors, just
1581         as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
1582         replicates the image edge color when it samples outside of its bounds.
1583 
1584         @param image   SkImage containing pixels, dimensions, and format
1585         @param center  SkIRect edge of image corners and sides
1586         @param dst     destination SkRect of image to draw to
1587         @param paint   SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1588                        and so on; or nullptr
1589     */
1590     void drawImageNine(const SkImage* image, const SkIRect& center, const SkRect& dst,
1591                        const SkPaint* paint = nullptr);
1592 
1593     /** Draw SkImage image stretched proportionally to fit into SkRect dst.
1594         SkIRect center divides the image into nine sections: four sides, four corners, and
1595         the center. Corners are not scaled, or scaled down proportionately if their sides
1596         are larger than dst; center and four sides are scaled to fit remaining space, if any.
1597 
1598         Additionally transform draw using clip, SkMatrix, and optional SkPaint paint.
1599 
1600         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1601         SkBlendMode, and SkDrawLooper. If image is kAlpha_8_SkColorType, apply SkShader.
1602         If paint contains SkMaskFilter, generate mask from bitmap bounds. If paint's
1603         SkFilterQuality is higher than kLow_SkFilterQuality, it will be treated as if it
1604         were kLow_SkFilterQuality.
1605 
1606         If generated mask extends beyond image bounds, replicate image edge colors, just
1607         as SkShader made from SkImage::makeShader with SkShader::kClamp_TileMode set
1608         replicates the image edge color when it samples outside of its bounds.
1609 
1610         @param image   SkImage containing pixels, dimensions, and format
1611         @param center  SkIRect edge of image corners and sides
1612         @param dst     destination SkRect of image to draw to
1613         @param paint   SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1614                        and so on; or nullptr
1615     */
1616     void drawImageNine(const sk_sp<SkImage>& image, const SkIRect& center, const SkRect& dst,
1617                        const SkPaint* paint = nullptr) {
1618         this->drawImageNine(image.get(), center, dst, paint);
1619     }
1620 
1621     /** Draw SkBitmap bitmap, with its top-left corner at (left, top),
1622         using clip, SkMatrix, and optional SkPaint paint.
1623 
1624         If SkPaint paint is not nullptr, apply SkColorFilter, color alpha, SkImageFilter,
1625         SkBlendMode, and SkDrawLooper. If bitmap is kAlpha_8_SkColorType, apply SkShader.
1626         If paint contains SkMaskFilter, generate mask from bitmap bounds.
1627 
1628         If generated mask extends beyond bitmap bounds, replicate bitmap edge colors,
1629         just as SkShader made from SkShader::MakeBitmapShader with
1630         SkShader::kClamp_TileMode set replicates the bitmap edge color when it samples
1631         outside of its bounds.
1632 
1633         @param bitmap  SkBitmap containing pixels, dimensions, and format
1634         @param left    left side of bitmap
1635         @param top     top side of bitmap
1636         @param paint   SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1637                        and so on; or nullptr
1638     */
1639     void drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top,
1640                     const SkPaint* paint = nullptr);
1641 
1642     /** Draw SkRect src of SkBitmap bitmap, scaled and translated to fill SkRect dst.
1643         Additionally transform draw using clip, SkMatrix, and optional SkPaint paint.
1644 
1645         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1646         SkBlendMode, and SkDrawLooper. If bitmap is kAlpha_8_SkColorType, apply SkShader.
1647         If paint contains SkMaskFilter, generate mask from bitmap bounds.
1648 
1649         If generated mask extends beyond bitmap bounds, replicate bitmap edge colors,
1650         just as SkShader made from SkShader::MakeBitmapShader with
1651         SkShader::kClamp_TileMode set replicates the bitmap edge color when it samples
1652         outside of its bounds.
1653 
1654         constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
1655         sample within src; set to kFast_SrcRectConstraint allows sampling outside to
1656         improve performance.
1657 
1658         @param bitmap      SkBitmap containing pixels, dimensions, and format
1659         @param src         source SkRect of image to draw from
1660         @param dst         destination SkRect of image to draw to
1661         @param paint       SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1662                            and so on; or nullptr
1663         @param constraint  filter strictly within src or draw faster
1664     */
1665     void drawBitmapRect(const SkBitmap& bitmap, const SkRect& src, const SkRect& dst,
1666                         const SkPaint* paint,
1667                         SrcRectConstraint constraint = kStrict_SrcRectConstraint);
1668 
1669     /** Draw SkIRect isrc of SkBitmap bitmap, scaled and translated to fill SkRect dst.
1670         isrc is on integer pixel boundaries; dst may include fractional boundaries.
1671         Additionally transform draw using clip, SkMatrix, and optional SkPaint paint.
1672 
1673         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1674         SkBlendMode, and SkDrawLooper. If bitmap is kAlpha_8_SkColorType, apply SkShader.
1675         If paint contains SkMaskFilter, generate mask from bitmap bounds.
1676 
1677         If generated mask extends beyond bitmap bounds, replicate bitmap edge colors,
1678         just as SkShader made from SkShader::MakeBitmapShader with
1679         SkShader::kClamp_TileMode set replicates the bitmap edge color when it samples
1680         outside of its bounds.
1681 
1682         constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
1683         sample within isrc; set to kFast_SrcRectConstraint allows sampling outside to
1684         improve performance.
1685 
1686         @param bitmap      SkBitmap containing pixels, dimensions, and format
1687         @param isrc        source SkIRect of image to draw from
1688         @param dst         destination SkRect of image to draw to
1689         @param paint       SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1690                            and so on; or nullptr
1691         @param constraint  sample strictly within isrc, or draw faster
1692     */
1693     void drawBitmapRect(const SkBitmap& bitmap, const SkIRect& isrc, const SkRect& dst,
1694                         const SkPaint* paint,
1695                         SrcRectConstraint constraint = kStrict_SrcRectConstraint);
1696 
1697     /** Draw SkBitmap bitmap, scaled and translated to fill SkRect dst.
1698         bitmap bounds is on integer pixel boundaries; dst may include fractional boundaries.
1699         Additionally transform draw using clip, SkMatrix, and optional SkPaint paint.
1700 
1701         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1702         SkBlendMode, and SkDrawLooper. If bitmap is kAlpha_8_SkColorType, apply SkShader.
1703         If paint contains SkMaskFilter, generate mask from bitmap bounds.
1704 
1705         If generated mask extends beyond bitmap bounds, replicate bitmap edge colors,
1706         just as SkShader made from SkShader::MakeBitmapShader with
1707         SkShader::kClamp_TileMode set replicates the bitmap edge color when it samples
1708         outside of its bounds.
1709 
1710         constraint set to kStrict_SrcRectConstraint limits SkPaint SkFilterQuality to
1711         sample within bitmap; set to kFast_SrcRectConstraint allows sampling outside to
1712         improve performance.
1713 
1714         @param bitmap      SkBitmap containing pixels, dimensions, and format
1715         @param dst         destination SkRect of image to draw to
1716         @param paint       SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1717                            and so on; or nullptr
1718         @param constraint  filter strictly within bitmap or draw faster
1719     */
1720     void drawBitmapRect(const SkBitmap& bitmap, const SkRect& dst, const SkPaint* paint,
1721                         SrcRectConstraint constraint = kStrict_SrcRectConstraint);
1722 
1723     /** Draw SkBitmap bitmap stretched proportionally to fit into SkRect dst.
1724         SkIRect center divides the bitmap into nine sections: four sides, four corners,
1725         and the center. Corners are not scaled, or scaled down proportionately if their
1726         sides are larger than dst; center and four sides are scaled to fit remaining
1727         space, if any.
1728 
1729         Additionally transform draw using clip, SkMatrix, and optional SkPaint paint.
1730 
1731         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1732         SkBlendMode, and SkDrawLooper. If bitmap is kAlpha_8_SkColorType, apply SkShader.
1733         If paint contains SkMaskFilter, generate mask from bitmap bounds. If paint's
1734         SkFilterQuality is higher than kLow_SkFilterQuality, it will be treated as if it
1735         were kLow_SkFilterQuality.
1736 
1737         If generated mask extends beyond bitmap bounds, replicate bitmap edge colors,
1738         just as SkShader made from SkShader::MakeBitmapShader with
1739         SkShader::kClamp_TileMode set replicates the bitmap edge color when it samples
1740         outside of its bounds.
1741 
1742         @param bitmap  SkBitmap containing pixels, dimensions, and format
1743         @param center  SkIRect edge of image corners and sides
1744         @param dst     destination SkRect of image to draw to
1745         @param paint   SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1746                        and so on; or nullptr
1747     */
1748     void drawBitmapNine(const SkBitmap& bitmap, const SkIRect& center, const SkRect& dst,
1749                         const SkPaint* paint = nullptr);
1750 
1751     /** \struct SkCanvas::Lattice
1752         SkCanvas::Lattice divides SkBitmap or SkImage into a rectangular grid.
1753         Grid entries on even columns and even rows are fixed; these entries are
1754         always drawn at their original size if the destination is large enough.
1755         If the destination side is too small to hold the fixed entries, all fixed
1756         entries are proportionately scaled down to fit.
1757         The grid entries not on even columns and rows are scaled to fit the
1758         remaining space, if any.
1759     */
1760     struct Lattice {
1761 
1762         /** \enum SkCanvas::Lattice::RectType
1763             Optional setting per rectangular grid entry to make it transparent,
1764             or to fill the grid entry with a color.
1765         */
1766         enum RectType : uint8_t {
1767             kDefault     = 0, //!< Draws SkBitmap into lattice rectangle.
1768             kTransparent,     //!< Skips lattice rectangle by making it transparent.
1769             kFixedColor,      //!< Draws one of fColors into lattice rectangle.
1770         };
1771 
1772         /** Array of x-coordinates that divide the bitmap vertically.
1773             Array entries must be unique, increasing, greater than or equal to
1774             fBounds left edge, and less than fBounds right edge.
1775             Set the first element to fBounds left to collapse the left column of
1776             fixed grid entries.
1777         */
1778         const int*      fXDivs;
1779 
1780         /** Array of y-coordinates that divide the bitmap horizontally.
1781             Array entries must be unique, increasing, greater than or equal to
1782             fBounds top edge, and less than fBounds bottom edge.
1783             Set the first element to fBounds top to collapse the top row of fixed
1784             grid entries.
1785         */
1786         const int*      fYDivs;
1787 
1788         /** Optional array of fill types, one per rectangular grid entry:
1789             array length must be (fXCount + 1) * (fYCount + 1).
1790 
1791             Each RectType is one of: kDefault, kTransparent, kFixedColor.
1792 
1793             Array entries correspond to the rectangular grid entries, ascending
1794             left to right and then top to bottom.
1795         */
1796         const RectType* fRectTypes;
1797 
1798         /** Number of entries in fXDivs array; one less than the number of
1799             horizontal divisions.
1800         */
1801         int             fXCount;
1802 
1803         /** Number of entries in fYDivs array; one less than the number of vertical
1804             divisions.
1805         */
1806         int             fYCount;
1807 
1808         /** Optional subset SkIRect source to draw from.
1809             If nullptr, source bounds is dimensions of SkBitmap or SkImage.
1810         */
1811         const SkIRect*  fBounds;
1812 
1813         /** Optional array of colors, one per rectangular grid entry.
1814             Array length must be (fXCount + 1) * (fYCount + 1).
1815 
1816             Array entries correspond to the rectangular grid entries, ascending
1817             left to right, then top to bottom.
1818         */
1819         const SkColor*  fColors;
1820 
1821     };
1822 
1823     /** Draw SkBitmap bitmap stretched proportionally to fit into SkRect dst.
1824 
1825         SkCanvas::Lattice lattice divides bitmap into a rectangular grid.
1826         Each intersection of an even-numbered row and column is fixed; like the corners
1827         of drawBitmapNine(), fixed lattice elements never scale larger than their initial
1828         size and shrink proportionately when all fixed elements exceed the bitmap
1829         dimension. All other grid elements scale to fill the available space, if any.
1830 
1831         Additionally transform draw using clip, SkMatrix, and optional SkPaint paint.
1832 
1833         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1834         SkBlendMode, and SkDrawLooper. If bitmap is kAlpha_8_SkColorType, apply SkShader.
1835         If paint contains SkMaskFilter, generate mask from bitmap bounds. If paint's
1836         SkFilterQuality is higher than kLow_SkFilterQuality, it will be treated as if it
1837         were kLow_SkFilterQuality.
1838 
1839         If generated mask extends beyond bitmap bounds, replicate bitmap edge colors,
1840         just as SkShader made from SkShader::MakeBitmapShader with
1841         SkShader::kClamp_TileMode set replicates the bitmap edge color when it samples
1842         outside of its bounds.
1843 
1844         @param bitmap   SkBitmap containing pixels, dimensions, and format
1845         @param lattice  division of bitmap into fixed and variable rectangles
1846         @param dst      destination SkRect of image to draw to
1847         @param paint    SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1848                         and so on; or nullptr
1849     */
1850     void drawBitmapLattice(const SkBitmap& bitmap, const Lattice& lattice, const SkRect& dst,
1851                            const SkPaint* paint = nullptr);
1852 
1853     /** Draw SkImage image stretched proportionally to fit into SkRect dst.
1854 
1855         SkCanvas::Lattice lattice divides image into a rectangular grid.
1856         Each intersection of an even-numbered row and column is fixed; like the corners
1857         of drawBitmapNine(), fixed lattice elements never scale larger than their initial
1858         size and shrink proportionately when all fixed elements exceed the bitmap
1859         dimension. All other grid elements scale to fill the available space, if any.
1860 
1861         Additionally transform draw using clip, SkMatrix, and optional SkPaint paint.
1862 
1863         If SkPaint paint is supplied, apply SkColorFilter, color alpha, SkImageFilter,
1864         SkBlendMode, and SkDrawLooper. If bitmap is kAlpha_8_SkColorType, apply SkShader.
1865         If paint contains SkMaskFilter, generate mask from bitmap bounds. If paint's
1866         SkFilterQuality is higher than kLow_SkFilterQuality, it will be treated as if it
1867         were kLow_SkFilterQuality.
1868 
1869         If generated mask extends beyond bitmap bounds, replicate bitmap edge colors,
1870         just as SkShader made from SkShader::MakeBitmapShader with
1871         SkShader::kClamp_TileMode set replicates the bitmap edge color when it samples
1872         outside of its bounds.
1873 
1874         @param image    SkImage containing pixels, dimensions, and format
1875         @param lattice  division of bitmap into fixed and variable rectangles
1876         @param dst      destination SkRect of image to draw to
1877         @param paint    SkPaint containing SkBlendMode, SkColorFilter, SkImageFilter,
1878                         and so on; or nullptr
1879     */
1880     void drawImageLattice(const SkImage* image, const Lattice& lattice, const SkRect& dst,
1881                           const SkPaint* paint = nullptr);
1882 
1883     /** Draw text, with origin at (x, y), using clip, SkMatrix, and SkPaint paint.
1884 
1885         text meaning depends on SkPaint::TextEncoding; by default, text is encoded as
1886         UTF-8.
1887 
1888         x and y meaning depends on SkPaint::Align and SkPaint vertical text; by default
1889         text draws left to right, positioning the first glyph left side bearing at x
1890         and its baseline at y. Text size is affected by SkMatrix and SkPaint text size.
1891 
1892         All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
1893         SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
1894         filled 12 point black glyphs.
1895 
1896         @param text        character code points or glyphs drawn
1897         @param byteLength  byte length of text array
1898         @param x           start of text on x-axis
1899         @param y           start of text on y-axis
1900         @param paint       text size, blend, color, and so on, used to draw
1901     */
1902     void drawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
1903                   const SkPaint& paint);
1904 
1905     /** Draw null terminated string, with origin at (x, y), using clip, SkMatrix, and
1906         SkPaint paint.
1907 
1908         string meaning depends on SkPaint::TextEncoding; by default, strings are encoded
1909         as UTF-8. Other values of SkPaint::TextEncoding are unlikely to produce the desired
1910         results, since zero bytes may be embedded in the string.
1911 
1912         x and y meaning depends on SkPaint::Align and SkPaint vertical text; by default
1913         string draws left to right, positioning the first glyph left side bearing at x
1914         and its baseline at y. Text size is affected by SkMatrix and SkPaint text size.
1915 
1916         All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
1917         SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
1918         filled 12 point black glyphs.
1919 
1920         @param string  character code points or glyphs drawn,
1921                        ending with a char value of zero
1922         @param x       start of string on x-axis
1923         @param y       start of string on y-axis
1924         @param paint   text size, blend, color, and so on, used to draw
1925     */
drawString(const char * string,SkScalar x,SkScalar y,const SkPaint & paint)1926     void drawString(const char* string, SkScalar x, SkScalar y, const SkPaint& paint) {
1927         if (!string) {
1928             return;
1929         }
1930         this->drawText(string, strlen(string), x, y, paint);
1931     }
1932 
1933     /** Draw null terminated string, with origin at (x, y), using clip, SkMatrix, and
1934         SkPaint paint.
1935 
1936         string meaning depends on SkPaint::TextEncoding; by default, strings are encoded
1937         as UTF-8. Other values of SkPaint::TextEncoding are unlikely to produce the desired
1938         results, since zero bytes may be embedded in the string.
1939 
1940         x and y meaning depends on SkPaint::Align and SkPaint vertical text; by default
1941         string draws left to right, positioning the first glyph left side bearing at x
1942         and its baseline at y. Text size is affected by SkMatrix and SkPaint text size.
1943 
1944         All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
1945         SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
1946         filled 12 point black glyphs.
1947 
1948         @param string  character code points or glyphs drawn,
1949                        ending with a char value of zero
1950         @param x       start of string on x-axis
1951         @param y       start of string on y-axis
1952         @param paint   text size, blend, color, and so on, used to draw
1953     */
1954     void drawString(const SkString& string, SkScalar x, SkScalar y, const SkPaint& paint);
1955 
1956     /** Draw each glyph in text with the origin in pos array, using clip, SkMatrix, and
1957         SkPaint paint. The number of entries in pos array must match the number of glyphs
1958         described by byteLength of text.
1959 
1960         text meaning depends on SkPaint::TextEncoding; by default, text is encoded as
1961         UTF-8. pos elements' meaning depends on SkPaint::Align and SkPaint vertical text;
1962         by default each glyph left side bearing is positioned at x and its
1963         baseline is positioned at y. Text size is affected by SkMatrix and
1964         SkPaint text size.
1965 
1966         All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
1967         SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
1968         filled 12 point black glyphs.
1969 
1970         Layout engines such as Harfbuzz typically position each glyph
1971         rather than using the font advance widths.
1972 
1973         @param text        character code points or glyphs drawn
1974         @param byteLength  byte length of text array
1975         @param pos         array of glyph origins
1976         @param paint       text size, blend, color, and so on, used to draw
1977     */
1978     void drawPosText(const void* text, size_t byteLength, const SkPoint pos[],
1979                      const SkPaint& paint);
1980 
1981     /** Draw each glyph in text with its (x, y) origin composed from xpos array and
1982         constY, using clip, SkMatrix, and SkPaint paint. The number of entries in xpos array
1983         must match the number of glyphs described by byteLength of text.
1984 
1985         text meaning depends on SkPaint::TextEncoding; by default, text is encoded as
1986         UTF-8. xpos elements' meaning depends on SkPaint::Align and SkPaint vertical text;
1987         by default each glyph left side bearing is positioned at an xpos element and
1988         its baseline is positioned at constY. Text size is affected by SkMatrix and
1989         SkPaint text size.
1990 
1991         All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
1992         SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
1993         filled 12 point black glyphs.
1994 
1995         Layout engines such as Harfbuzz typically position each glyph
1996         rather than using the font advance widths if all glyphs share the same
1997         baseline.
1998 
1999         @param text        character code points or glyphs drawn
2000         @param byteLength  byte length of text array
2001         @param xpos        array of x positions, used to position each glyph
2002         @param constY      shared y coordinate for all of x positions
2003         @param paint       text size, blend, color, and so on, used to draw
2004     */
2005     void drawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[], SkScalar constY,
2006                       const SkPaint& paint);
2007 
2008     /** Draw text on SkPath path, using clip, SkMatrix, and SkPaint paint.
2009 
2010         Origin of text is at distance hOffset along the path, offset by a perpendicular
2011         vector of length vOffset. If the path section corresponding the glyph advance is
2012         curved, the glyph is drawn curved to match; control points in the glyph are
2013         mapped to projected points parallel to the path. If the text advance is larger
2014         than the path length, the excess text is clipped.
2015 
2016         text meaning depends on SkPaint::TextEncoding; by default, text is encoded as
2017         UTF-8. Origin meaning depends on SkPaint::Align and SkPaint vertical text; by
2018         default text positions the first glyph left side bearing at origin x and its
2019         baseline at origin y. Text size is affected by SkMatrix and SkPaint text size.
2020 
2021         All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
2022         SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
2023         filled 12 point black glyphs.
2024 
2025         @param text        character code points or glyphs drawn
2026         @param byteLength  byte length of text array
2027         @param path        SkPath providing text baseline
2028         @param hOffset     distance along path to offset origin
2029         @param vOffset     offset of text above (if negative) or below (if positive) the path
2030         @param paint       text size, blend, color, and so on, used to draw
2031     */
2032     void drawTextOnPathHV(const void* text, size_t byteLength, const SkPath& path, SkScalar hOffset,
2033                           SkScalar vOffset, const SkPaint& paint);
2034 
2035     /** Draw text on SkPath path, using clip, SkMatrix, and SkPaint paint.
2036 
2037         Origin of text is at beginning of path offset by matrix, if provided, before it
2038         is mapped to path. If the path section corresponding the glyph advance is
2039         curved, the glyph is drawn curved to match; control points in the glyph are
2040         mapped to projected points parallel to the path. If the text advance is larger
2041         than the path length, the excess text is clipped.
2042 
2043         text meaning depends on SkPaint::TextEncoding; by default, text is encoded as
2044         UTF-8. Origin meaning depends on SkPaint::Align and SkPaint vertical text; by
2045         default text positions the first glyph left side bearing at origin x and its
2046         baseline at origin y. Text size is affected by SkMatrix and SkPaint text size.
2047 
2048         All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
2049         SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
2050         filled 12 point black glyphs.
2051 
2052         @param text        character code points or glyphs drawn
2053         @param byteLength  byte length of text array
2054         @param path        SkPath providing text baseline
2055         @param matrix      transform of glyphs before mapping to path; may be nullptr
2056                            to use identity SkMatrix
2057         @param paint       text size, blend, color, and so on, used to draw
2058     */
2059     void drawTextOnPath(const void* text, size_t byteLength, const SkPath& path,
2060                         const SkMatrix* matrix, const SkPaint& paint);
2061 
2062     /** Draw text, transforming each glyph by the corresponding SkRSXform,
2063         using clip, SkMatrix, and SkPaint paint.
2064 
2065         SkRSXform array specifies a separate square scale, rotation, and translation for
2066         each glyph. Note that this per-glyph xform does not affect the shader (if present)
2067         on the paint, just the glyph's geometry.
2068 
2069         Optional SkRect cullRect is a conservative bounds of text, taking into account
2070         SkRSXform and paint. If cullRect is outside of clip, canvas can skip drawing.
2071 
2072         All elements of paint: SkPathEffect, SkMaskFilter, SkShader,
2073         SkColorFilter, SkImageFilter, and SkDrawLooper; apply to text. By default, draws
2074         filled 12 point black glyphs.
2075 
2076         @param text        character code points or glyphs drawn
2077         @param byteLength  byte length of text array
2078         @param xform       SkRSXform rotates, scales, and translates each glyph individually
2079         @param cullRect    SkRect bounds of text for efficient clipping; or nullptr
2080         @param paint       text size, blend, color, and so on, used to draw
2081     */
2082     void drawTextRSXform(const void* text, size_t byteLength, const SkRSXform xform[],
2083                          const SkRect* cullRect, const SkPaint& paint);
2084 
2085     /** Draw SkTextBlob blob at (x, y), using clip, SkMatrix, and SkPaint paint.
2086 
2087         blob contains glyphs, their positions, and paint attributes specific to text:
2088         SkTypeface, SkPaint text size, SkPaint text scale x, SkPaint text skew x,
2089         SkPaint::Align, SkPaint::Hinting, SkPaint anti-alias, SkPaint fake bold,
2090         SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
2091         SkPaint subpixel text, and SkPaint vertical text.
2092 
2093         SkPaint::TextEncoding must be set to SkPaint::kGlyphID_TextEncoding.
2094 
2095         Elements of paint: SkPathEffect, SkMaskFilter, SkShader, SkColorFilter,
2096         SkImageFilter, and SkDrawLooper; apply to blob.
2097 
2098         @param blob   glyphs, positions, and their paints' text size, typeface, and so on
2099         @param x      horizontal offset applied to blob
2100         @param y      vertical offset applied to blob
2101         @param paint  blend, color, stroking, and so on, used to draw
2102     */
2103     void drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y, const SkPaint& paint);
2104 
2105     /** Draw SkTextBlob blob at (x, y), using clip, SkMatrix, and SkPaint paint.
2106 
2107         blob contains glyphs, their positions, and paint attributes specific to text:
2108         SkTypeface, SkPaint text size, SkPaint text scale x, SkPaint text skew x,
2109         SkPaint::Align, SkPaint::Hinting, SkPaint anti-alias, SkPaint fake bold,
2110         SkPaint font embedded bitmaps, SkPaint full hinting spacing, LCD text, SkPaint linear text,
2111         SkPaint subpixel text, and SkPaint vertical text.
2112 
2113         SkPaint::TextEncoding must be set to SkPaint::kGlyphID_TextEncoding.
2114 
2115         Elements of paint: SkPathEffect, SkMaskFilter, SkShader, SkColorFilter,
2116         SkImageFilter, and SkDrawLooper; apply to blob.
2117 
2118         @param blob   glyphs, positions, and their paints' text size, typeface, and so on
2119         @param x      horizontal offset applied to blob
2120         @param y      vertical offset applied to blob
2121         @param paint  blend, color, stroking, and so on, used to draw
2122     */
drawTextBlob(const sk_sp<SkTextBlob> & blob,SkScalar x,SkScalar y,const SkPaint & paint)2123     void drawTextBlob(const sk_sp<SkTextBlob>& blob, SkScalar x, SkScalar y, const SkPaint& paint) {
2124         this->drawTextBlob(blob.get(), x, y, paint);
2125     }
2126 
2127     /** Draw SkPicture picture, using clip and SkMatrix.
2128         Clip and SkMatrix are unchanged by picture contents, as if
2129         save() was called before and restore() was called after drawPicture().
2130 
2131         SkPicture records a series of draw commands for later playback.
2132 
2133         @param picture  recorded drawing commands to play
2134     */
drawPicture(const SkPicture * picture)2135     void drawPicture(const SkPicture* picture) {
2136         this->drawPicture(picture, nullptr, nullptr);
2137     }
2138 
2139     /** Draw SkPicture picture, using clip and SkMatrix.
2140         Clip and SkMatrix are unchanged by picture contents, as if
2141         save() was called before and restore() was called after drawPicture().
2142 
2143         SkPicture records a series of draw commands for later playback.
2144 
2145         @param picture  recorded drawing commands to play
2146     */
drawPicture(const sk_sp<SkPicture> & picture)2147     void drawPicture(const sk_sp<SkPicture>& picture) {
2148         this->drawPicture(picture.get());
2149     }
2150 
2151     /** Draw SkPicture picture, using clip and SkMatrix; transforming picture with
2152         SkMatrix matrix, if provided; and use SkPaint paint color alpha, SkColorFilter,
2153         SkImageFilter, and SkBlendMode, if provided.
2154 
2155         matrix transformation is equivalent to: save(), concat(), drawPicture(), restore().
2156         paint use is equivalent to: saveLayer(), drawPicture(), restore().
2157 
2158         @param picture  recorded drawing commands to play
2159         @param matrix   SkMatrix to rotate, scale, translate, and so on; may be nullptr
2160         @param paint    SkPaint to apply transparency, filtering, and so on; may be nullptr
2161     */
2162     void drawPicture(const SkPicture* picture, const SkMatrix* matrix, const SkPaint* paint);
2163 
2164     /** Draw SkPicture picture, using clip and SkMatrix; transforming picture with
2165         SkMatrix matrix, if provided; and use SkPaint paint color alpha, SkColorFilter,
2166         SkImageFilter, and SkBlendMode, if provided.
2167 
2168         matrix transformation is equivalent to: save(), concat(), drawPicture(), restore().
2169         paint use is equivalent to: saveLayer(), drawPicture(), restore().
2170 
2171         @param picture  recorded drawing commands to play
2172         @param matrix   SkMatrix to rotate, scale, translate, and so on; may be nullptr
2173         @param paint    SkPaint to apply transparency, filtering, and so on; may be nullptr
2174     */
drawPicture(const sk_sp<SkPicture> & picture,const SkMatrix * matrix,const SkPaint * paint)2175     void drawPicture(const sk_sp<SkPicture>& picture, const SkMatrix* matrix, const SkPaint* paint) {
2176         this->drawPicture(picture.get(), matrix, paint);
2177     }
2178 
2179     /** Draw vertices vertices, a triangle mesh, using clip and SkMatrix.
2180         If vertices texs and vertices colors are defined in vertices, and SkPaint paint
2181         contains SkShader, SkBlendMode mode combines vertices colors with SkShader.
2182 
2183         @param vertices  triangle mesh to draw
2184         @param mode      combines vertices colors with SkShader, if both are present
2185         @param paint     specifies the SkShader, used as vertices texture; may be nullptr
2186     */
2187     void drawVertices(const SkVertices* vertices, SkBlendMode mode, const SkPaint& paint);
2188 
2189     /** Draw vertices vertices, a triangle mesh, using clip and SkMatrix.
2190         If vertices texs and vertices colors are defined in vertices, and SkPaint paint
2191         contains SkShader, SkBlendMode mode combines vertices colors with SkShader.
2192 
2193         @param vertices  triangle mesh to draw
2194         @param mode      combines vertices colors with SkShader, if both are present
2195         @param paint     specifies the SkShader, used as vertices texture, may be nullptr
2196     */
2197     void drawVertices(const sk_sp<SkVertices>& vertices, SkBlendMode mode, const SkPaint& paint);
2198 
2199     /** Draws a Coons_Patch: the interpolation of four cubics with shared corners,
2200         associating a color, and optionally a texture coordinate, with each corner.
2201 
2202         Coons_Patch uses clip and SkMatrix, paint SkShader, SkColorFilter,
2203         color alpha, SkImageFilter, and SkBlendMode. If SkShader is provided it is treated
2204         as Coons_Patch texture; SkBlendMode mode combines color colors and SkShader if
2205         both are provided.
2206 
2207         SkPoint array cubics specifies four SkPath cubic starting at the top-left corner,
2208         in clockwise order, sharing every fourth point. The last SkPath cubic ends at the
2209         first point.
2210 
2211         Color array color associates colors with corners in top-left, top-right,
2212         bottom-right, bottom-left order.
2213 
2214         If paint contains SkShader, SkPoint array texCoords maps SkShader as texture to
2215         corners in top-left, top-right, bottom-right, bottom-left order.
2216 
2217         @param cubics     SkPath cubic array, sharing common points
2218         @param colors     color array, one for each corner
2219         @param texCoords  SkPoint array of texture coordinates, mapping SkShader to corners;
2220                           may be nullptr
2221         @param mode       SkBlendMode for colors, and for SkShader if paint has one
2222         @param paint      SkShader, SkColorFilter, SkBlendMode, used to draw
2223     */
2224     void drawPatch(const SkPoint cubics[12], const SkColor colors[4],
2225                    const SkPoint texCoords[4], SkBlendMode mode, const SkPaint& paint);
2226 
2227     /** Draws SkPath cubic Coons_Patch: the interpolation of four cubics with shared corners,
2228         associating a color, and optionally a texture coordinate, with each corner.
2229 
2230         Coons_Patch uses clip and SkMatrix, paint SkShader, SkColorFilter,
2231         color alpha, SkImageFilter, and SkBlendMode. If SkShader is provided it is treated
2232         as Coons_Patch texture; SkBlendMode mode combines color colors and SkShader if
2233         both are provided.
2234 
2235         SkPoint array cubics specifies four SkPath cubic starting at the top-left corner,
2236         in clockwise order, sharing every fourth point. The last SkPath cubic ends at the
2237         first point.
2238 
2239         Color array color associates colors with corners in top-left, top-right,
2240         bottom-right, bottom-left order.
2241 
2242         If paint contains SkShader, SkPoint array texCoords maps SkShader as texture to
2243         corners in top-left, top-right, bottom-right, bottom-left order.
2244 
2245         @param cubics     SkPath cubic array, sharing common points
2246         @param colors     color array, one for each corner
2247         @param texCoords  SkPoint array of texture coordinates, mapping SkShader to corners;
2248                           may be nullptr
2249         @param paint      SkShader, SkColorFilter, SkBlendMode, used to draw
2250     */
drawPatch(const SkPoint cubics[12],const SkColor colors[4],const SkPoint texCoords[4],const SkPaint & paint)2251     void drawPatch(const SkPoint cubics[12], const SkColor colors[4],
2252                    const SkPoint texCoords[4], const SkPaint& paint) {
2253         this->drawPatch(cubics, colors, texCoords, SkBlendMode::kModulate, paint);
2254     }
2255 
2256     /** Draw a set of sprites from atlas, using clip, SkMatrix, and optional SkPaint paint.
2257         paint uses SkPaint anti-alias, color alpha, SkColorFilter, SkImageFilter, and SkBlendMode
2258         to draw, if present. For each entry in the array, SkRect tex locates sprite in
2259         atlas, and SkRSXform xform transforms it into destination space.
2260 
2261         xform, text, and colors if present, must contain count entries.
2262         Optional colors are applied for each sprite using SkBlendMode.
2263         Optional cullRect is a conservative bounds of all transformed sprites.
2264         If cullRect is outside of clip, canvas can skip drawing.
2265 
2266         @param atlas     SkImage containing sprites
2267         @param xform     SkRSXform mappings for sprites in atlas
2268         @param tex       SkRect locations of sprites in atlas
2269         @param colors    one per sprite, blended with sprite using SkBlendMode; may be nullptr
2270         @param count     number of sprites to draw
2271         @param mode      SkBlendMode combining colors and sprites
2272         @param cullRect  bounds of transformed sprites for efficient clipping; may be nullptr
2273         @param paint     SkColorFilter, SkImageFilter, SkBlendMode, and so on; may be nullptr
2274     */
2275     void drawAtlas(const SkImage* atlas, const SkRSXform xform[], const SkRect tex[],
2276                    const SkColor colors[], int count, SkBlendMode mode, const SkRect* cullRect,
2277                    const SkPaint* paint);
2278 
2279     /** Draw a set of sprites from atlas, using clip, SkMatrix, and optional SkPaint paint.
2280         paint uses SkPaint anti-alias, color alpha, SkColorFilter, SkImageFilter, and SkBlendMode
2281         to draw, if present. For each entry in the array, SkRect tex locates sprite in
2282         atlas, and SkRSXform xform transforms it into destination space.
2283 
2284         xform, text, and colors if present, must contain count entries.
2285         Optional colors is applied for each sprite using SkBlendMode.
2286         Optional cullRect is a conservative bounds of all transformed sprites.
2287         If cullRect is outside of clip, canvas can skip drawing.
2288 
2289         @param atlas     SkImage containing sprites
2290         @param xform     SkRSXform mappings for sprites in atlas
2291         @param tex       SkRect locations of sprites in atlas
2292         @param colors    one per sprite, blended with sprite using SkBlendMode; may be nullptr
2293         @param count     number of sprites to draw
2294         @param mode      SkBlendMode combining colors and sprites
2295         @param cullRect  bounds of transformed sprites for efficient clipping; may be nullptr
2296         @param paint     SkColorFilter, SkImageFilter, SkBlendMode, and so on; may be nullptr
2297     */
drawAtlas(const sk_sp<SkImage> & atlas,const SkRSXform xform[],const SkRect tex[],const SkColor colors[],int count,SkBlendMode mode,const SkRect * cullRect,const SkPaint * paint)2298     void drawAtlas(const sk_sp<SkImage>& atlas, const SkRSXform xform[], const SkRect tex[],
2299                    const SkColor colors[], int count, SkBlendMode mode, const SkRect* cullRect,
2300                    const SkPaint* paint) {
2301         this->drawAtlas(atlas.get(), xform, tex, colors, count, mode, cullRect, paint);
2302     }
2303 
2304     /** Draw a set of sprites from atlas, using clip, SkMatrix, and optional SkPaint paint.
2305         paint uses SkPaint anti-alias, color alpha, SkColorFilter, SkImageFilter, and SkBlendMode
2306         to draw, if present. For each entry in the array, SkRect tex locates sprite in
2307         atlas, and SkRSXform xform transforms it into destination space.
2308 
2309         xform and text must contain count entries.
2310         Optional cullRect is a conservative bounds of all transformed sprites.
2311         If cullRect is outside of clip, canvas can skip drawing.
2312 
2313         @param atlas     SkImage containing sprites
2314         @param xform     SkRSXform mappings for sprites in atlas
2315         @param tex       SkRect locations of sprites in atlas
2316         @param count     number of sprites to draw
2317         @param cullRect  bounds of transformed sprites for efficient clipping; may be nullptr
2318         @param paint     SkColorFilter, SkImageFilter, SkBlendMode, and so on; may be nullptr
2319     */
drawAtlas(const SkImage * atlas,const SkRSXform xform[],const SkRect tex[],int count,const SkRect * cullRect,const SkPaint * paint)2320     void drawAtlas(const SkImage* atlas, const SkRSXform xform[], const SkRect tex[], int count,
2321                    const SkRect* cullRect, const SkPaint* paint) {
2322         this->drawAtlas(atlas, xform, tex, nullptr, count, SkBlendMode::kDst, cullRect, paint);
2323     }
2324 
2325     /** Draw a set of sprites from atlas, using clip, SkMatrix, and optional SkPaint paint.
2326         paint uses SkPaint anti-alias, color alpha, SkColorFilter, SkImageFilter, and SkBlendMode
2327         to draw, if present. For each entry in the array, SkRect tex locates sprite in
2328         atlas, and SkRSXform xform transforms it into destination space.
2329 
2330         xform and text must contain count entries.
2331         Optional cullRect is a conservative bounds of all transformed sprites.
2332         If cullRect is outside of clip, canvas can skip drawing.
2333 
2334         @param atlas     SkImage containing sprites
2335         @param xform     SkRSXform mappings for sprites in atlas
2336         @param tex       SkRect locations of sprites in atlas
2337         @param count     number of sprites to draw
2338         @param cullRect  bounds of transformed sprites for efficient clipping; may be nullptr
2339         @param paint     SkColorFilter, SkImageFilter, SkBlendMode, and so on; may be nullptr
2340     */
drawAtlas(const sk_sp<SkImage> & atlas,const SkRSXform xform[],const SkRect tex[],int count,const SkRect * cullRect,const SkPaint * paint)2341     void drawAtlas(const sk_sp<SkImage>& atlas, const SkRSXform xform[], const SkRect tex[],
2342                    int count, const SkRect* cullRect, const SkPaint* paint) {
2343         this->drawAtlas(atlas.get(), xform, tex, nullptr, count, SkBlendMode::kDst,
2344                         cullRect, paint);
2345     }
2346 
2347     /** Draw SkDrawable drawable using clip and SkMatrix, concatenated with
2348         optional matrix.
2349 
2350         If SkCanvas has an asynchronous implementation, as is the case
2351         when it is recording into SkPicture, then drawable will be referenced,
2352         so that SkDrawable::draw() can be called when the operation is finalized. To force
2353         immediate drawing, call SkDrawable::draw() instead.
2354 
2355         @param drawable  custom struct encapsulating drawing commands
2356         @param matrix    transformation applied to drawing; may be nullptr
2357     */
2358     void drawDrawable(SkDrawable* drawable, const SkMatrix* matrix = nullptr);
2359 
2360     /** Draw SkDrawable drawable using clip and SkMatrix, offset by (x, y).
2361 
2362         If SkCanvas has an asynchronous implementation, as is the case
2363         when it is recording into SkPicture, then drawable will be referenced,
2364         so that SkDrawable::draw() can be called when the operation is finalized. To force
2365         immediate drawing, call SkDrawable::draw() instead.
2366 
2367         @param drawable  custom struct encapsulating drawing commands
2368         @param x         offset into SkCanvas writable pixels in x
2369         @param y         offset into SkCanvas writable pixels in y
2370     */
2371     void drawDrawable(SkDrawable* drawable, SkScalar x, SkScalar y);
2372 
2373     /** Associate SkRect on SkCanvas with an annotation; a key-value pair, where the key is
2374         a null-terminated utf8 string, and optional value is stored as SkData.
2375 
2376         Only some canvas implementations, such as recording to SkPicture, or drawing to
2377         document pdf, use annotations.
2378 
2379         @param rect   SkRect extent of canvas to annotate
2380         @param key    string used for lookup
2381         @param value  data holding value stored in annotation
2382     */
2383     void drawAnnotation(const SkRect& rect, const char key[], SkData* value);
2384 
2385     /** Associate SkRect on SkCanvas when an annotation; a key-value pair, where the key is
2386         a null-terminated utf8 string, and optional value is stored as SkData.
2387 
2388         Only some canvas implementations, such as recording to SkPicture, or drawing to
2389         document pdf, use annotations.
2390 
2391         @param rect   SkRect extent of canvas to annotate
2392         @param key    string used for lookup
2393         @param value  data holding value stored in annotation
2394     */
drawAnnotation(const SkRect & rect,const char key[],const sk_sp<SkData> & value)2395     void drawAnnotation(const SkRect& rect, const char key[], const sk_sp<SkData>& value) {
2396         this->drawAnnotation(rect, key, value.get());
2397     }
2398 
2399     //////////////////////////////////////////////////////////////////////////
2400 
2401 #ifdef SK_SUPPORT_LEGACY_DRAWFILTER
2402     /** To be deprecated soon.
2403     */
2404     SkDrawFilter* getDrawFilter() const;
2405 
2406     /** To be deprecated soon.
2407     */
2408     virtual SkDrawFilter* setDrawFilter(SkDrawFilter* filter);
2409 #endif
2410 
2411     /** Returns true if clip is empty; that is, nothing will draw.
2412 
2413         May do work when called; it should not be called
2414         more often than needed. However, once called, subsequent calls perform no
2415         work until clip changes.
2416 
2417         @return  true if clip is empty
2418     */
2419     virtual bool isClipEmpty() const;
2420 
2421     /** Returns true if clip is SkRect and not empty.
2422         Returns false if the clip is empty, or if it is not SkRect.
2423 
2424         @return  true if clip is SkRect and not empty
2425     */
2426     virtual bool isClipRect() const;
2427 
2428     /** Returns SkMatrix.
2429         This does not account for translation by SkBaseDevice or SkSurface.
2430 
2431         @return  SkMatrix in SkCanvas
2432     */
2433     const SkMatrix& getTotalMatrix() const;
2434 
2435     ///////////////////////////////////////////////////////////////////////////
2436 
2437     // don't call
2438     virtual GrRenderTargetContext* internal_private_accessTopLayerRenderTargetContext();
internal_private_getTopLayerBounds()2439     SkIRect internal_private_getTopLayerBounds() const { return getTopLayerBounds(); }
2440 
2441     // don't call
2442     static void Internal_Private_SetIgnoreSaveLayerBounds(bool);
2443     static bool Internal_Private_GetIgnoreSaveLayerBounds();
2444     static void Internal_Private_SetTreatSpriteAsBitmap(bool);
2445     static bool Internal_Private_GetTreatSpriteAsBitmap();
2446 
2447     // TEMP helpers until we switch virtual over to const& for src-rect
2448     void legacy_drawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst,
2449                               const SkPaint* paint,
2450                               SrcRectConstraint constraint = kStrict_SrcRectConstraint);
2451     void legacy_drawBitmapRect(const SkBitmap& bitmap, const SkRect* src, const SkRect& dst,
2452                                const SkPaint* paint,
2453                                SrcRectConstraint constraint = kStrict_SrcRectConstraint);
2454 
2455     /**
2456      *  Returns the global clip as a region. If the clip contains AA, then only the bounds
2457      *  of the clip may be returned.
2458      */
2459     void temporary_internal_getRgnClip(SkRegion* region);
2460 
2461     void private_draw_shadow_rec(const SkPath&, const SkDrawShadowRec&);
2462 
2463 protected:
2464     // default impl defers to getDevice()->newSurface(info)
2465     virtual sk_sp<SkSurface> onNewSurface(const SkImageInfo& info, const SkSurfaceProps& props);
2466 
2467     // default impl defers to its device
2468     virtual bool onPeekPixels(SkPixmap* pixmap);
2469     virtual bool onAccessTopLayerPixels(SkPixmap* pixmap);
2470     virtual SkImageInfo onImageInfo() const;
2471     virtual bool onGetProps(SkSurfaceProps* props) const;
2472     virtual void onFlush();
2473 
2474     // Subclass save/restore notifiers.
2475     // Overriders should call the corresponding INHERITED method up the inheritance chain.
2476     // getSaveLayerStrategy()'s return value may suppress full layer allocation.
2477     enum SaveLayerStrategy {
2478         kFullLayer_SaveLayerStrategy,
2479         kNoLayer_SaveLayerStrategy,
2480     };
2481 
willSave()2482     virtual void willSave() {}
2483     // Overriders should call the corresponding INHERITED method up the inheritance chain.
getSaveLayerStrategy(const SaveLayerRec &)2484     virtual SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec& ) {
2485         return kFullLayer_SaveLayerStrategy;
2486     }
willRestore()2487     virtual void willRestore() {}
didRestore()2488     virtual void didRestore() {}
didConcat(const SkMatrix &)2489     virtual void didConcat(const SkMatrix& ) {}
didSetMatrix(const SkMatrix &)2490     virtual void didSetMatrix(const SkMatrix& ) {}
didTranslate(SkScalar dx,SkScalar dy)2491     virtual void didTranslate(SkScalar dx, SkScalar dy) {
2492         this->didConcat(SkMatrix::MakeTrans(dx, dy));
2493     }
2494 
2495     virtual void onDrawAnnotation(const SkRect& rect, const char key[], SkData* value);
2496     virtual void onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint);
2497 
2498     virtual void onDrawText(const void* text, size_t byteLength, SkScalar x,
2499                             SkScalar y, const SkPaint& paint);
2500 
2501     virtual void onDrawPosText(const void* text, size_t byteLength,
2502                                const SkPoint pos[], const SkPaint& paint);
2503 
2504     virtual void onDrawPosTextH(const void* text, size_t byteLength,
2505                                 const SkScalar xpos[], SkScalar constY,
2506                                 const SkPaint& paint);
2507 
2508     virtual void onDrawTextOnPath(const void* text, size_t byteLength,
2509                                   const SkPath& path, const SkMatrix* matrix,
2510                                   const SkPaint& paint);
2511     virtual void onDrawTextRSXform(const void* text, size_t byteLength, const SkRSXform xform[],
2512                                    const SkRect* cullRect, const SkPaint& paint);
2513 
2514     virtual void onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
2515                                 const SkPaint& paint);
2516 
2517     virtual void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
2518                            const SkPoint texCoords[4], SkBlendMode mode, const SkPaint& paint);
2519 
2520     virtual void onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix);
2521 
2522     virtual void onDrawPaint(const SkPaint& paint);
2523     virtual void onDrawRect(const SkRect& rect, const SkPaint& paint);
2524     virtual void onDrawRegion(const SkRegion& region, const SkPaint& paint);
2525     virtual void onDrawOval(const SkRect& rect, const SkPaint& paint);
2526     virtual void onDrawArc(const SkRect& rect, SkScalar startAngle, SkScalar sweepAngle,
2527                            bool useCenter, const SkPaint& paint);
2528     virtual void onDrawRRect(const SkRRect& rrect, const SkPaint& paint);
2529     virtual void onDrawPoints(PointMode mode, size_t count, const SkPoint pts[],
2530                               const SkPaint& paint);
2531     virtual void onDrawVerticesObject(const SkVertices* vertices, SkBlendMode mode,
2532                                       const SkPaint& paint);
2533     virtual void onDrawAtlas(const SkImage* atlas, const SkRSXform xform[], const SkRect rect[],
2534                              const SkColor colors[], int count, SkBlendMode mode,
2535                              const SkRect* cull, const SkPaint* paint);
2536     virtual void onDrawPath(const SkPath& path, const SkPaint& paint);
2537     virtual void onDrawImage(const SkImage* image, SkScalar dx, SkScalar dy, const SkPaint* paint);
2538     virtual void onDrawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst,
2539                                  const SkPaint* paint, SrcRectConstraint constraint);
2540     virtual void onDrawImageNine(const SkImage* image, const SkIRect& center, const SkRect& dst,
2541                                  const SkPaint* paint);
2542     virtual void onDrawImageLattice(const SkImage* image, const Lattice& lattice, const SkRect& dst,
2543                                     const SkPaint* paint);
2544 
2545     virtual void onDrawBitmap(const SkBitmap& bitmap, SkScalar dx, SkScalar dy,
2546                               const SkPaint* paint);
2547     virtual void onDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src, const SkRect& dst,
2548                                   const SkPaint* paint, SrcRectConstraint constraint);
2549     virtual void onDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center, const SkRect& dst,
2550                                   const SkPaint* paint);
2551     virtual void onDrawBitmapLattice(const SkBitmap& bitmap, const Lattice& lattice,
2552                                      const SkRect& dst, const SkPaint* paint);
2553     virtual void onDrawShadowRec(const SkPath&, const SkDrawShadowRec&);
2554 
2555     enum ClipEdgeStyle {
2556         kHard_ClipEdgeStyle,
2557         kSoft_ClipEdgeStyle
2558     };
2559 
2560     virtual void onClipRect(const SkRect& rect, SkClipOp op, ClipEdgeStyle edgeStyle);
2561     virtual void onClipRRect(const SkRRect& rrect, SkClipOp op, ClipEdgeStyle edgeStyle);
2562     virtual void onClipPath(const SkPath& path, SkClipOp op, ClipEdgeStyle edgeStyle);
2563     virtual void onClipRegion(const SkRegion& deviceRgn, SkClipOp op);
2564 
2565     virtual void onDiscard();
2566 
2567     virtual void onDrawPicture(const SkPicture* picture, const SkMatrix* matrix,
2568                                const SkPaint* paint);
2569 
2570     // Clip rectangle bounds. Called internally by saveLayer.
2571     // returns false if the entire rectangle is entirely clipped out
2572     // If non-NULL, The imageFilter parameter will be used to expand the clip
2573     // and offscreen bounds for any margin required by the filter DAG.
2574     bool clipRectBounds(const SkRect* bounds, SaveLayerFlags flags, SkIRect* intersection,
2575                         const SkImageFilter* imageFilter = nullptr);
2576 
2577 private:
2578     /** After calling saveLayer(), there can be any number of devices that make
2579      up the top-most drawing area. LayerIter can be used to iterate through
2580      those devices. Note that the iterator is only valid until the next API
2581      call made on the canvas. Ownership of all pointers in the iterator stays
2582      with the canvas, so none of them should be modified or deleted.
2583      */
2584     class LayerIter /*: SkNoncopyable*/ {
2585     public:
2586         /** Initialize iterator with canvas, and set values for 1st device */
2587         LayerIter(SkCanvas*);
2588         ~LayerIter();
2589 
2590         /** Return true if the iterator is done */
done()2591         bool done() const { return fDone; }
2592         /** Cycle to the next device */
2593         void next();
2594 
2595         // These reflect the current device in the iterator
2596 
2597         SkBaseDevice*   device() const;
2598         const SkMatrix& matrix() const;
2599         void clip(SkRegion*) const;
2600         const SkPaint&  paint() const;
2601         int             x() const;
2602         int             y() const;
2603 
2604     private:
2605         // used to embed the SkDrawIter object directly in our instance, w/o
2606         // having to expose that class def to the public. There is an assert
2607         // in our constructor to ensure that fStorage is large enough
2608         // (though needs to be a compile-time-assert!). We use intptr_t to work
2609         // safely with 32 and 64 bit machines (to ensure the storage is enough)
2610         intptr_t          fStorage[32];
2611         class SkDrawIter* fImpl;    // this points at fStorage
2612         SkPaint           fDefaultPaint;
2613         bool              fDone;
2614     };
2615 
2616     static bool BoundsAffectsClip(SaveLayerFlags);
2617     static SaveLayerFlags LegacySaveFlagsToSaveLayerFlags(uint32_t legacySaveFlags);
2618 
2619     static void DrawDeviceWithFilter(SkBaseDevice* src, const SkImageFilter* filter,
2620                                      SkBaseDevice* dst, const SkIPoint& dstOrigin,
2621                                      const SkMatrix& ctm);
2622 
2623     enum ShaderOverrideOpacity {
2624         kNone_ShaderOverrideOpacity,        //!< there is no overriding shader (bitmap or image)
2625         kOpaque_ShaderOverrideOpacity,      //!< the overriding shader is opaque
2626         kNotOpaque_ShaderOverrideOpacity,   //!< the overriding shader may not be opaque
2627     };
2628 
2629     // notify our surface (if we have one) that we are about to draw, so it
2630     // can perform copy-on-write or invalidate any cached images
2631     void predrawNotify(bool willOverwritesEntireSurface = false);
2632     void predrawNotify(const SkRect* rect, const SkPaint* paint, ShaderOverrideOpacity);
predrawNotify(const SkRect * rect,const SkPaint * paint,bool shaderOverrideIsOpaque)2633     void predrawNotify(const SkRect* rect, const SkPaint* paint, bool shaderOverrideIsOpaque) {
2634         this->predrawNotify(rect, paint, shaderOverrideIsOpaque ? kOpaque_ShaderOverrideOpacity
2635                                                                 : kNotOpaque_ShaderOverrideOpacity);
2636     }
2637 
2638     SkBaseDevice* getDevice() const;
2639     SkBaseDevice* getTopDevice() const;
2640 
2641     class MCRec;
2642 
2643     SkDeque     fMCStack;
2644     // points to top of stack
2645     MCRec*      fMCRec;
2646     // the first N recs that can fit here mean we won't call malloc
2647     enum {
2648         kMCRecSize      = 128,  // most recent measurement
2649         kMCRecCount     = 32,   // common depth for save/restores
2650         kDeviceCMSize   = 224,  // most recent measurement
2651     };
2652     intptr_t fMCRecStorage[kMCRecSize * kMCRecCount / sizeof(intptr_t)];
2653     intptr_t fDeviceCMStorage[kDeviceCMSize / sizeof(intptr_t)];
2654 
2655     const SkSurfaceProps fProps;
2656 
2657     int         fSaveCount;         // value returned by getSaveCount()
2658 
2659     SkMetaData* fMetaData;
2660     std::unique_ptr<SkRasterHandleAllocator> fAllocator;
2661 
2662     SkSurface_Base*  fSurfaceBase;
getSurfaceBase()2663     SkSurface_Base* getSurfaceBase() const { return fSurfaceBase; }
setSurfaceBase(SkSurface_Base * sb)2664     void setSurfaceBase(SkSurface_Base* sb) {
2665         fSurfaceBase = sb;
2666     }
2667     friend class SkSurface_Base;
2668     friend class SkSurface_Gpu;
2669 
2670     SkIRect fClipRestrictionRect = SkIRect::MakeEmpty();
2671 
2672     void doSave();
2673     void checkForDeferredSave();
2674     void internalSetMatrix(const SkMatrix&);
2675 
2676     friend class SkAndroidFrameworkUtils;
2677     friend class SkDrawIter;        // needs setupDrawForLayerDevice()
2678     friend class AutoDrawLooper;
2679     friend class SkDebugCanvas;     // needs experimental fAllowSimplifyClip
2680     friend class SkSurface_Raster;  // needs getDevice()
2681     friend class SkNoDrawCanvas;    // InitFlags
2682     friend class SkPictureImageFilter;  // SkCanvas(SkBaseDevice*, SkSurfaceProps*, InitFlags)
2683     friend class SkPictureRecord;   // predrawNotify (why does it need it? <reed>)
2684     friend class SkPicturePlayback; // SaveFlagsToSaveLayerFlags
2685     friend class SkOverdrawCanvas;
2686     friend class SkRasterHandleAllocator;
2687 
2688     enum InitFlags {
2689         kDefault_InitFlags                  = 0,
2690         kConservativeRasterClip_InitFlag    = 1 << 0,
2691     };
2692     SkCanvas(const SkIRect& bounds, InitFlags);
2693     SkCanvas(SkBaseDevice* device, InitFlags);
2694     SkCanvas(const SkBitmap&, std::unique_ptr<SkRasterHandleAllocator>,
2695              SkRasterHandleAllocator::Handle);
2696 
2697     void resetForNextPicture(const SkIRect& bounds);
2698 
2699     // needs gettotalclip()
2700     friend class SkCanvasStateUtils;
2701 
2702     // call this each time we attach ourselves to a device
2703     //  - constructor
2704     //  - internalSaveLayer
2705     void setupDevice(SkBaseDevice*);
2706 
2707     SkBaseDevice* init(SkBaseDevice*, InitFlags);
2708 
2709     /**
2710      * Gets the bounds of the top level layer in global canvas coordinates. We don't want this
2711      * to be public because it exposes decisions about layer sizes that are internal to the canvas.
2712      */
2713     SkIRect getTopLayerBounds() const;
2714 
2715     void internalDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src,
2716                                 const SkRect& dst, const SkPaint* paint,
2717                                 SrcRectConstraint);
2718     void internalDrawPaint(const SkPaint& paint);
2719     void internalSaveLayer(const SaveLayerRec&, SaveLayerStrategy);
2720     void internalDrawDevice(SkBaseDevice*, int x, int y, const SkPaint*, SkImage* clipImage,
2721                             const SkMatrix& clipMatrix);
2722 
2723     // shared by save() and saveLayer()
2724     void internalSave();
2725     void internalRestore();
2726 
2727     /*
2728      *  Returns true if drawing the specified rect (or all if it is null) with the specified
2729      *  paint (or default if null) would overwrite the entire root device of the canvas
2730      *  (i.e. the canvas' surface if it had one).
2731      */
2732     bool wouldOverwriteEntireSurface(const SkRect*, const SkPaint*, ShaderOverrideOpacity) const;
2733 
2734     /**
2735      *  Returns true if the paint's imagefilter can be invoked directly, without needed a layer.
2736      */
2737     bool canDrawBitmapAsSprite(SkScalar x, SkScalar y, int w, int h, const SkPaint&);
2738 
2739     /**
2740      *  Returns true if the clip (for any active layer) contains antialiasing.
2741      *  If the clip is empty, this will return false.
2742      */
2743     bool androidFramework_isClipAA() const;
2744 
2745     /**
2746      *  Keep track of the device clip bounds and if the matrix is scale-translate.  This allows
2747      *  us to do a fast quick reject in the common case.
2748      */
2749     bool   fIsScaleTranslate;
2750     SkRect fDeviceClipBounds;
2751 
2752     bool fAllowSoftClip;
2753     bool fAllowSimplifyClip;
2754 
2755     class AutoValidateClip : ::SkNoncopyable {
2756     public:
AutoValidateClip(SkCanvas * canvas)2757         explicit AutoValidateClip(SkCanvas* canvas) : fCanvas(canvas) {
2758             fCanvas->validateClip();
2759         }
~AutoValidateClip()2760         ~AutoValidateClip() { fCanvas->validateClip(); }
2761 
2762     private:
2763         const SkCanvas* fCanvas;
2764     };
2765 
2766 #ifdef SK_DEBUG
2767     void validateClip() const;
2768 #else
validateClip()2769     void validateClip() const {}
2770 #endif
2771 
2772     typedef SkRefCnt INHERITED;
2773 };
2774 
2775 /** \class SkAutoCanvasRestore
2776     Stack helper class calls SkCanvas::restoreToCount() when SkAutoCanvasRestore
2777     goes out of scope. Use this to guarantee that the canvas is restored to a known
2778     state.
2779 */
2780 class SkAutoCanvasRestore : SkNoncopyable {
2781 public:
2782 
2783     /** Preserves SkCanvas save count. Optionally saves SkCanvas clip and SkCanvas matrix.
2784 
2785         @param canvas  SkCanvas to guard
2786         @param doSave  call SkCanvas::save()
2787         @return        utility to restore SkCanvas state on destructor
2788     */
SkAutoCanvasRestore(SkCanvas * canvas,bool doSave)2789     SkAutoCanvasRestore(SkCanvas* canvas, bool doSave) : fCanvas(canvas), fSaveCount(0) {
2790         if (fCanvas) {
2791             fSaveCount = canvas->getSaveCount();
2792             if (doSave) {
2793                 canvas->save();
2794             }
2795         }
2796     }
2797 
2798     /** Restores SkCanvas to saved state. Destructor is called when container goes out of
2799         scope.
2800     */
~SkAutoCanvasRestore()2801     ~SkAutoCanvasRestore() {
2802         if (fCanvas) {
2803             fCanvas->restoreToCount(fSaveCount);
2804         }
2805     }
2806 
2807     /** Restores SkCanvas to saved state immediately. Subsequent calls and
2808         ~SkAutoCanvasRestore have no effect.
2809     */
restore()2810     void restore() {
2811         if (fCanvas) {
2812             fCanvas->restoreToCount(fSaveCount);
2813             fCanvas = nullptr;
2814         }
2815     }
2816 
2817 private:
2818     SkCanvas*   fCanvas;
2819     int         fSaveCount;
2820 };
2821 #define SkAutoCanvasRestore(...) SK_REQUIRE_LOCAL_VAR(SkAutoCanvasRestore)
2822 
2823 #endif
2824