2 * Copyright 2006 The Android Open Source Project
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #ifndef SkCanvas_DEFINED
9 #define SkCanvas_DEFINED
14 #include "SkClipStack.h"
19 #include "SkSurfaceProps.h"
20 #include "SkXfermode.h"
22 #ifdef SK_SUPPORT_LEGACY_DRAWTEXT_VIRTUAL
23 #define SK_LEGACY_DRAWTEXT_VIRTUAL virtual
25 #define SK_LEGACY_DRAWTEXT_VIRTUAL
28 class SkCanvasClipVisitor;
44 namespace SkCanvasStateUtils {
45 SK_API SkCanvasState* CaptureCanvasState(SkCanvas*);
50 A Canvas encapsulates all of the state about drawing into a device (bitmap).
51 This includes a reference to the device itself, and a stack of matrix/clip
52 values. For any given draw call (e.g. drawRect), the geometry of the object
53 being drawn is transformed by the concatenation of all the matrices in the
54 stack. The transformed geometry is clipped by the intersection of all of
55 the clips in the stack.
57 While the Canvas holds the state of the drawing device, the state (style)
58 of the object being drawn is held by the Paint, which is provided as a
59 parameter to each of the draw() methods. The Paint holds attributes such as
60 color, typeface, textSize, strokeWidth, shader (e.g. gradients, patterns),
63 class SK_API SkCanvas : public SkRefCnt {
65 SK_DECLARE_INST_COUNT(SkCanvas)
68 * Attempt to allocate an offscreen raster canvas, matching the ImageInfo.
69 * On success, return a new canvas that will draw into that offscreen.
71 * The caller can access the pixels after drawing into this canvas by
72 * calling readPixels() or peekPixels().
74 * If the requested ImageInfo is opaque (either the colortype is
75 * intrinsically opaque like RGB_565, or the info's alphatype is kOpaque)
76 * then the pixel memory may be uninitialized. Otherwise, the pixel memory
77 * will be initialized to 0, which is interpreted as transparent.
79 * On failure, return NULL. This can fail for several reasons:
80 * 1. the memory allocation failed (e.g. request is too large)
81 * 2. invalid ImageInfo (e.g. negative dimensions)
82 * 3. unsupported ImageInfo for a canvas
83 * - kUnknown_SkColorType, kIndex_8_SkColorType
84 * - kIgnore_SkAlphaType
85 * - this list is not complete, so others may also be unsupported
87 * Note: it is valid to request a supported ImageInfo, but with zero
90 static SkCanvas* NewRaster(const SkImageInfo&);
92 static SkCanvas* NewRasterN32(int width, int height) {
93 return NewRaster(SkImageInfo::MakeN32Premul(width, height));
97 * Attempt to allocate raster canvas, matching the ImageInfo, that will draw directly into the
98 * specified pixels. To access the pixels after drawing to them, the caller should call
99 * flush() or call peekPixels(...).
101 * On failure, return NULL. This can fail for several reasons:
102 * 1. invalid ImageInfo (e.g. negative dimensions)
103 * 2. unsupported ImageInfo for a canvas
104 * - kUnknown_SkColorType, kIndex_8_SkColorType
105 * - kIgnore_SkAlphaType
106 * - this list is not complete, so others may also be unsupported
108 * Note: it is valid to request a supported ImageInfo, but with zero
111 static SkCanvas* NewRasterDirect(const SkImageInfo&, void*, size_t);
113 static SkCanvas* NewRasterDirectN32(int width, int height, SkPMColor* pixels, size_t rowBytes) {
114 return NewRasterDirect(SkImageInfo::MakeN32Premul(width, height), pixels, rowBytes);
118 * Creates an empty canvas with no backing device/pixels, and zero
124 * Creates a canvas of the specified dimensions, but explicitly not backed
125 * by any device/pixels. Typically this use used by subclasses who handle
126 * the draw calls in some other way.
128 SkCanvas(int width, int height);
130 /** Construct a canvas with the specified device to draw into.
132 @param device Specifies a device for the canvas to draw into.
134 explicit SkCanvas(SkBaseDevice* device);
136 /** Construct a canvas with the specified bitmap to draw into.
137 @param bitmap Specifies a bitmap for the canvas to draw into. Its
138 structure are copied to the canvas.
140 explicit SkCanvas(const SkBitmap& bitmap);
143 SkMetaData& getMetaData();
146 * Return ImageInfo for this canvas. If the canvas is not backed by pixels
147 * (cpu or gpu), then the info's ColorType will be kUnknown_SkColorType.
149 SkImageInfo imageInfo() const;
151 ///////////////////////////////////////////////////////////////////////////
154 * Trigger the immediate execution of all pending draw operations.
159 * Gets the size of the base or root layer in global canvas coordinates. The
160 * origin of the base layer is always (0,0). The current drawable area may be
161 * smaller (due to clipping or saveLayer).
163 SkISize getBaseLayerSize() const;
166 * DEPRECATED: call getBaseLayerSize
168 SkISize getDeviceSize() const { return this->getBaseLayerSize(); }
172 * Return the canvas' device object, which may be null. The device holds
173 * the bitmap of the pixels that the canvas draws into. The reference count
174 * of the returned device is not changed by this call.
176 #ifndef SK_SUPPORT_LEGACY_GETDEVICE
177 protected: // Can we make this private?
179 SkBaseDevice* getDevice() const;
183 * saveLayer() can create another device (which is later drawn onto
184 * the previous device). getTopDevice() returns the top-most device current
185 * installed. Note that this can change on other calls like save/restore,
186 * so do not access this device after subsequent canvas calls.
187 * The reference count of the device is not changed.
189 * @param updateMatrixClip If this is true, then before the device is
190 * returned, we ensure that its has been notified about the current
191 * matrix and clip. Note: this happens automatically when the device
192 * is drawn to, but is optional here, as there is a small perf hit
195 #ifndef SK_SUPPORT_LEGACY_GETTOPDEVICE
198 SkBaseDevice* getTopDevice(bool updateMatrixClip = false) const;
202 * Create a new surface matching the specified info, one that attempts to
203 * be maximally compatible when used with this canvas. If there is no matching Surface type,
206 * If surfaceprops is specified, those are passed to the new surface, otherwise the new surface
207 * inherits the properties of the surface that owns this canvas. If this canvas has no parent
208 * surface, then the new surface is created with default properties.
210 SkSurface* newSurface(const SkImageInfo&, const SkSurfaceProps* = NULL);
213 * Return the GPU context of the device that is associated with the canvas.
214 * For a canvas with non-GPU device, NULL is returned.
216 GrContext* getGrContext();
218 ///////////////////////////////////////////////////////////////////////////
221 * If the canvas has writable pixels in its top layer (and is not recording to a picture
222 * or other non-raster target) and has direct access to its pixels (i.e. they are in
223 * local RAM) return the address of those pixels, and if not null,
224 * return the ImageInfo, rowBytes and origin. The returned address is only valid
225 * while the canvas object is in scope and unchanged. Any API calls made on
226 * canvas (or its parent surface if any) will invalidate the
227 * returned address (and associated information).
229 * On failure, returns NULL and the info, rowBytes, and origin parameters are ignored.
231 void* accessTopLayerPixels(SkImageInfo* info, size_t* rowBytes, SkIPoint* origin = NULL);
234 * If the canvas has readable pixels in its base layer (and is not recording to a picture
235 * or other non-raster target) and has direct access to its pixels (i.e. they are in
236 * local RAM) return the const-address of those pixels, and if not null,
237 * return the ImageInfo and rowBytes. The returned address is only valid
238 * while the canvas object is in scope and unchanged. Any API calls made on
239 * canvas (or its parent surface if any) will invalidate the
240 * returned address (and associated information).
242 * On failure, returns NULL and the info and rowBytes parameters are
245 const void* peekPixels(SkImageInfo* info, size_t* rowBytes);
248 * Copy the pixels from the base-layer into the specified buffer (pixels + rowBytes),
249 * converting them into the requested format (SkImageInfo). The base-layer pixels are read
250 * starting at the specified (srcX,srcY) location in the coordinate system of the base-layer.
252 * The specified ImageInfo and (srcX,srcY) offset specifies a source rectangle
254 * srcR.setXYWH(srcX, srcY, dstInfo.width(), dstInfo.height());
256 * srcR is intersected with the bounds of the base-layer. If this intersection is not empty,
257 * then we have two sets of pixels (of equal size). Replace the dst pixels with the
258 * corresponding src pixels, performing any colortype/alphatype transformations needed
259 * (in the case where the src and dst have different colortypes or alphatypes).
261 * This call can fail, returning false, for several reasons:
262 * - If srcR does not intersect the base-layer bounds.
263 * - If the requested colortype/alphatype cannot be converted from the base-layer's types.
264 * - If this canvas is not backed by pixels (e.g. picture or PDF)
266 bool readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
270 * Helper for calling readPixels(info, ...). This call will check if bitmap has been allocated.
271 * If not, it will attempt to call allocPixels(). If this fails, it will return false. If not,
272 * it calls through to readPixels(info, ...) and returns its result.
274 bool readPixels(SkBitmap* bitmap, int srcX, int srcY);
277 * Helper for allocating pixels and then calling readPixels(info, ...). The bitmap is resized
278 * to the intersection of srcRect and the base-layer bounds. On success, pixels will be
279 * allocated in bitmap and true returned. On failure, false is returned and bitmap will be
282 bool readPixels(const SkIRect& srcRect, SkBitmap* bitmap);
285 * This method affects the pixels in the base-layer, and operates in pixel coordinates,
286 * ignoring the matrix and clip.
288 * The specified ImageInfo and (x,y) offset specifies a rectangle: target.
290 * target.setXYWH(x, y, info.width(), info.height());
292 * Target is intersected with the bounds of the base-layer. If this intersection is not empty,
293 * then we have two sets of pixels (of equal size), the "src" specified by info+pixels+rowBytes
294 * and the "dst" by the canvas' backend. Replace the dst pixels with the corresponding src
295 * pixels, performing any colortype/alphatype transformations needed (in the case where the
296 * src and dst have different colortypes or alphatypes).
298 * This call can fail, returning false, for several reasons:
299 * - If the src colortype/alphatype cannot be converted to the canvas' types
300 * - If this canvas is not backed by pixels (e.g. picture or PDF)
302 bool writePixels(const SkImageInfo&, const void* pixels, size_t rowBytes, int x, int y);
305 * Helper for calling writePixels(info, ...) by passing its pixels and rowbytes. If the bitmap
306 * is just wrapping a texture, returns false and does nothing.
308 bool writePixels(const SkBitmap& bitmap, int x, int y);
310 ///////////////////////////////////////////////////////////////////////////
313 /** save the matrix state, restoring it on restore() */
314 // [deprecated] kMatrix_SaveFlag = 0x01,
315 kMatrix_SaveFlag = 0x01,
316 /** save the clip state, restoring it on restore() */
317 // [deprecated] kClip_SaveFlag = 0x02,
318 kClip_SaveFlag = 0x02,
319 /** the layer needs to support per-pixel alpha */
320 kHasAlphaLayer_SaveFlag = 0x04,
321 /** the layer needs to support 8-bits per color component */
322 kFullColorLayer_SaveFlag = 0x08,
324 * the layer should clip against the bounds argument
326 * if SK_SUPPORT_LEGACY_CLIPTOLAYERFLAG is undefined, this is treated as always on.
328 kClipToLayer_SaveFlag = 0x10,
330 // helper masks for common choices
331 // [deprecated] kMatrixClip_SaveFlag = 0x03,
332 kMatrixClip_SaveFlag = 0x03,
333 #ifdef SK_SUPPORT_LEGACY_CLIPTOLAYERFLAG
334 kARGB_NoClipLayer_SaveFlag = 0x0F,
336 kARGB_ClipLayer_SaveFlag = 0x1F
339 /** This call saves the current matrix, clip, and drawFilter, and pushes a
340 copy onto a private stack. Subsequent calls to translate, scale,
341 rotate, skew, concat or clipRect, clipPath, and setDrawFilter all
342 operate on this copy.
343 When the balancing call to restore() is made, the previous matrix, clip,
344 and drawFilter are restored.
346 @return The value to pass to restoreToCount() to balance this save()
350 /** This behaves the same as save(), but in addition it allocates an
351 offscreen bitmap. All drawing calls are directed there, and only when
352 the balancing call to restore() is made is that offscreen transfered to
353 the canvas (or the previous layer).
354 @param bounds (may be null) This rect, if non-null, is used as a hint to
355 limit the size of the offscreen, and thus drawing may be
356 clipped to it, though that clipping is not guaranteed to
357 happen. If exact clipping is desired, use clipRect().
358 @param paint (may be null) This is copied, and is applied to the
359 offscreen when restore() is called
360 @return The value to pass to restoreToCount() to balance this save()
362 int saveLayer(const SkRect* bounds, const SkPaint* paint);
364 /** DEPRECATED - use saveLayer(const SkRect*, const SkPaint*) instead.
366 This behaves the same as saveLayer(const SkRect*, const SkPaint*),
367 but it allows fine-grained control of which state bits to be saved
368 (and subsequently restored).
370 @param bounds (may be null) This rect, if non-null, is used as a hint to
371 limit the size of the offscreen, and thus drawing may be
372 clipped to it, though that clipping is not guaranteed to
373 happen. If exact clipping is desired, use clipRect().
374 @param paint (may be null) This is copied, and is applied to the
375 offscreen when restore() is called
376 @param flags LayerFlags
377 @return The value to pass to restoreToCount() to balance this save()
379 SK_ATTR_EXTERNALLY_DEPRECATED("SaveFlags use is deprecated")
380 int saveLayer(const SkRect* bounds, const SkPaint* paint, SaveFlags flags);
382 /** This behaves the same as save(), but in addition it allocates an
383 offscreen bitmap. All drawing calls are directed there, and only when
384 the balancing call to restore() is made is that offscreen transfered to
385 the canvas (or the previous layer).
386 @param bounds (may be null) This rect, if non-null, is used as a hint to
387 limit the size of the offscreen, and thus drawing may be
388 clipped to it, though that clipping is not guaranteed to
389 happen. If exact clipping is desired, use clipRect().
390 @param alpha This is applied to the offscreen when restore() is called.
391 @return The value to pass to restoreToCount() to balance this save()
393 int saveLayerAlpha(const SkRect* bounds, U8CPU alpha);
395 /** DEPRECATED - use saveLayerAlpha(const SkRect*, U8CPU) instead.
397 This behaves the same as saveLayerAlpha(const SkRect*, U8CPU),
398 but it allows fine-grained control of which state bits to be saved
399 (and subsequently restored).
401 @param bounds (may be null) This rect, if non-null, is used as a hint to
402 limit the size of the offscreen, and thus drawing may be
403 clipped to it, though that clipping is not guaranteed to
404 happen. If exact clipping is desired, use clipRect().
405 @param alpha This is applied to the offscreen when restore() is called.
406 @param flags LayerFlags
407 @return The value to pass to restoreToCount() to balance this save()
409 SK_ATTR_EXTERNALLY_DEPRECATED("SaveFlags use is deprecated")
410 int saveLayerAlpha(const SkRect* bounds, U8CPU alpha, SaveFlags flags);
412 /** This call balances a previous call to save(), and is used to remove all
413 modifications to the matrix/clip/drawFilter state since the last save
415 It is an error to call restore() more times than save() was called.
419 /** Returns the number of matrix/clip states on the SkCanvas' private stack.
420 This will equal # save() calls - # restore() calls + 1. The save count on
423 int getSaveCount() const;
425 /** Efficient way to pop any calls to save() that happened after the save
426 count reached saveCount. It is an error for saveCount to be greater than
427 getSaveCount(). To pop all the way back to the initial matrix/clip context
429 @param saveCount The number of save() levels to restore from
431 void restoreToCount(int saveCount);
433 /** Returns true if drawing is currently going to a layer (from saveLayer)
434 * rather than to the root device.
436 virtual bool isDrawingToLayer() const;
438 /** Preconcat the current matrix with the specified translation
439 @param dx The distance to translate in X
440 @param dy The distance to translate in Y
442 void translate(SkScalar dx, SkScalar dy);
444 /** Preconcat the current matrix with the specified scale.
445 @param sx The amount to scale in X
446 @param sy The amount to scale in Y
448 void scale(SkScalar sx, SkScalar sy);
450 /** Preconcat the current matrix with the specified rotation.
451 @param degrees The amount to rotate, in degrees
453 void rotate(SkScalar degrees);
455 /** Preconcat the current matrix with the specified skew.
456 @param sx The amount to skew in X
457 @param sy The amount to skew in Y
459 void skew(SkScalar sx, SkScalar sy);
461 /** Preconcat the current matrix with the specified matrix.
462 @param matrix The matrix to preconcatenate with the current matrix
464 void concat(const SkMatrix& matrix);
466 /** Replace the current matrix with a copy of the specified matrix.
467 @param matrix The matrix that will be copied into the current matrix.
469 void setMatrix(const SkMatrix& matrix);
471 /** Helper for setMatrix(identity). Sets the current matrix to identity.
476 * Modify the current clip with the specified rectangle.
477 * @param rect The rect to combine with the current clip
478 * @param op The region op to apply to the current clip
479 * @param doAntiAlias true if the clip should be antialiased
481 void clipRect(const SkRect& rect,
482 SkRegion::Op op = SkRegion::kIntersect_Op,
483 bool doAntiAlias = false);
486 * Modify the current clip with the specified SkRRect.
487 * @param rrect The rrect to combine with the current clip
488 * @param op The region op to apply to the current clip
489 * @param doAntiAlias true if the clip should be antialiased
491 void clipRRect(const SkRRect& rrect,
492 SkRegion::Op op = SkRegion::kIntersect_Op,
493 bool doAntiAlias = false);
496 * Modify the current clip with the specified path.
497 * @param path The path to combine with the current clip
498 * @param op The region op to apply to the current clip
499 * @param doAntiAlias true if the clip should be antialiased
501 void clipPath(const SkPath& path,
502 SkRegion::Op op = SkRegion::kIntersect_Op,
503 bool doAntiAlias = false);
505 /** EXPERIMENTAL -- only used for testing
506 Set to false to force clips to be hard, even if doAntiAlias=true is
507 passed to clipRect or clipPath.
509 void setAllowSoftClip(bool allow) {
510 fAllowSoftClip = allow;
513 /** EXPERIMENTAL -- only used for testing
514 Set to simplify clip stack using path ops.
516 void setAllowSimplifyClip(bool allow) {
517 fAllowSimplifyClip = allow;
520 /** Modify the current clip with the specified region. Note that unlike
521 clipRect() and clipPath() which transform their arguments by the current
522 matrix, clipRegion() assumes its argument is already in device
523 coordinates, and so no transformation is performed.
524 @param deviceRgn The region to apply to the current clip
525 @param op The region op to apply to the current clip
527 void clipRegion(const SkRegion& deviceRgn,
528 SkRegion::Op op = SkRegion::kIntersect_Op);
530 /** Helper for clipRegion(rgn, kReplace_Op). Sets the current clip to the
531 specified region. This does not intersect or in any other way account
532 for the existing clip region.
533 @param deviceRgn The region to copy into the current clip.
535 void setClipRegion(const SkRegion& deviceRgn) {
536 this->clipRegion(deviceRgn, SkRegion::kReplace_Op);
539 /** Return true if the specified rectangle, after being transformed by the
540 current matrix, would lie completely outside of the current clip. Call
541 this to check if an area you intend to draw into is clipped out (and
542 therefore you can skip making the draw calls).
543 @param rect the rect to compare with the current clip
544 @return true if the rect (transformed by the canvas' matrix) does not
545 intersect with the canvas' clip
547 bool quickReject(const SkRect& rect) const;
549 /** Return true if the specified path, after being transformed by the
550 current matrix, would lie completely outside of the current clip. Call
551 this to check if an area you intend to draw into is clipped out (and
552 therefore you can skip making the draw calls). Note, for speed it may
553 return false even if the path itself might not intersect the clip
554 (i.e. the bounds of the path intersects, but the path does not).
555 @param path The path to compare with the current clip
556 @return true if the path (transformed by the canvas' matrix) does not
557 intersect with the canvas' clip
559 bool quickReject(const SkPath& path) const;
561 /** Return true if the horizontal band specified by top and bottom is
562 completely clipped out. This is a conservative calculation, meaning
563 that it is possible that if the method returns false, the band may still
564 in fact be clipped out, but the converse is not true. If this method
565 returns true, then the band is guaranteed to be clipped out.
566 @param top The top of the horizontal band to compare with the clip
567 @param bottom The bottom of the horizontal and to compare with the clip
568 @return true if the horizontal band is completely clipped out (i.e. does
569 not intersect the current clip)
571 bool quickRejectY(SkScalar top, SkScalar bottom) const {
572 SkASSERT(top <= bottom);
574 #ifndef SK_WILL_NEVER_DRAW_PERSPECTIVE_TEXT
575 // TODO: add a hasPerspective method similar to getLocalClipBounds. This
576 // would cache the SkMatrix::hasPerspective result. Alternatively, have
577 // the MC stack just set a hasPerspective boolean as it is updated.
578 if (this->getTotalMatrix().hasPerspective()) {
579 // TODO: consider implementing some half-plane test between the
580 // two Y planes and the device-bounds (i.e., project the top and
581 // bottom Y planes and then determine if the clip bounds is completely
582 // outside either one).
587 const SkRect& clipR = this->getLocalClipBounds();
588 // In the case where the clip is empty and we are provided with a
589 // negative top and positive bottom parameter then this test will return
590 // false even though it will be clipped. We have chosen to exclude that
591 // check as it is rare and would result double the comparisons.
592 return top >= clipR.fBottom || bottom <= clipR.fTop;
595 /** Return the bounds of the current clip (in local coordinates) in the
596 bounds parameter, and return true if it is non-empty. This can be useful
597 in a way similar to quickReject, in that it tells you that drawing
598 outside of these bounds will be clipped out.
600 virtual bool getClipBounds(SkRect* bounds) const;
602 /** Return the bounds of the current clip, in device coordinates; returns
603 true if non-empty. Maybe faster than getting the clip explicitly and
604 then taking its bounds.
606 virtual bool getClipDeviceBounds(SkIRect* bounds) const;
609 /** Fill the entire canvas' bitmap (restricted to the current clip) with the
610 specified ARGB color, using the specified mode.
611 @param a the alpha component (0..255) of the color to fill the canvas
612 @param r the red component (0..255) of the color to fill the canvas
613 @param g the green component (0..255) of the color to fill the canvas
614 @param b the blue component (0..255) of the color to fill the canvas
615 @param mode the mode to apply the color in (defaults to SrcOver)
617 void drawARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b,
618 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode);
620 /** Fill the entire canvas' bitmap (restricted to the current clip) with the
621 specified color and mode.
622 @param color the color to draw with
623 @param mode the mode to apply the color in (defaults to SrcOver)
625 void drawColor(SkColor color,
626 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode);
629 * This erases the entire drawing surface to the specified color,
630 * irrespective of the clip. It does not blend with the previous pixels,
631 * but always overwrites them.
633 * It is roughly equivalent to the following:
635 * canvas.clipRect(hugeRect, kReplace_Op);
636 * paint.setColor(color);
637 * paint.setXfermodeMode(kSrc_Mode);
638 * canvas.drawPaint(paint);
640 * though it is almost always much more efficient.
642 virtual void clear(SkColor);
645 * This makes the contents of the canvas undefined. Subsequent calls that
646 * require reading the canvas contents will produce undefined results. Examples
647 * include blending and readPixels. The actual implementation is backend-
648 * dependent and one legal implementation is to do nothing. Like clear(), this
651 * This function should only be called if the caller intends to subsequently
652 * draw to the canvas. The canvas may do real work at discard() time in order
653 * to optimize performance on subsequent draws. Thus, if you call this and then
654 * never draw to the canvas subsequently you may pay a perfomance penalty.
656 void discard() { this->onDiscard(); }
659 * Fill the entire canvas' bitmap (restricted to the current clip) with the
661 * @param paint The paint used to fill the canvas
663 virtual void drawPaint(const SkPaint& paint);
666 /** drawPoints draws each point separately */
668 /** drawPoints draws each pair of points as a line segment */
670 /** drawPoints draws the array of points as a polygon */
674 /** Draw a series of points, interpreted based on the PointMode mode. For
675 all modes, the count parameter is interpreted as the total number of
676 points. For kLine mode, count/2 line segments are drawn.
677 For kPoint mode, each point is drawn centered at its coordinate, and its
678 size is specified by the paint's stroke-width. It draws as a square,
679 unless the paint's cap-type is round, in which the points are drawn as
681 For kLine mode, each pair of points is drawn as a line segment,
682 respecting the paint's settings for cap/join/width.
683 For kPolygon mode, the entire array is drawn as a series of connected
685 Note that, while similar, kLine and kPolygon modes draw slightly
686 differently than the equivalent path built with a series of moveto,
687 lineto calls, in that the path will draw all of its contours at once,
688 with no interactions if contours intersect each other (think XOR
689 xfermode). drawPoints always draws each element one at a time.
690 @param mode PointMode specifying how to draw the array of points.
691 @param count The number of points in the array
692 @param pts Array of points to draw
693 @param paint The paint used to draw the points
695 virtual void drawPoints(PointMode mode, size_t count, const SkPoint pts[],
696 const SkPaint& paint);
698 /** Helper method for drawing a single point. See drawPoints() for a more
701 void drawPoint(SkScalar x, SkScalar y, const SkPaint& paint);
703 /** Draws a single pixel in the specified color.
704 @param x The X coordinate of which pixel to draw
705 @param y The Y coordiante of which pixel to draw
706 @param color The color to draw
708 void drawPoint(SkScalar x, SkScalar y, SkColor color);
710 /** Draw a line segment with the specified start and stop x,y coordinates,
711 using the specified paint. NOTE: since a line is always "framed", the
712 paint's Style is ignored.
713 @param x0 The x-coordinate of the start point of the line
714 @param y0 The y-coordinate of the start point of the line
715 @param x1 The x-coordinate of the end point of the line
716 @param y1 The y-coordinate of the end point of the line
717 @param paint The paint used to draw the line
719 void drawLine(SkScalar x0, SkScalar y0, SkScalar x1, SkScalar y1,
720 const SkPaint& paint);
722 /** Draw the specified rectangle using the specified paint. The rectangle
723 will be filled or stroked based on the Style in the paint.
724 @param rect The rect to be drawn
725 @param paint The paint used to draw the rect
727 virtual void drawRect(const SkRect& rect, const SkPaint& paint);
729 /** Draw the specified rectangle using the specified paint. The rectangle
730 will be filled or framed based on the Style in the paint.
731 @param rect The rect to be drawn
732 @param paint The paint used to draw the rect
734 void drawIRect(const SkIRect& rect, const SkPaint& paint) {
736 r.set(rect); // promotes the ints to scalars
737 this->drawRect(r, paint);
740 /** Draw the specified rectangle using the specified paint. The rectangle
741 will be filled or framed based on the Style in the paint.
742 @param left The left side of the rectangle to be drawn
743 @param top The top side of the rectangle to be drawn
744 @param right The right side of the rectangle to be drawn
745 @param bottom The bottom side of the rectangle to be drawn
746 @param paint The paint used to draw the rect
748 void drawRectCoords(SkScalar left, SkScalar top, SkScalar right,
749 SkScalar bottom, const SkPaint& paint);
751 /** Draw the specified oval using the specified paint. The oval will be
752 filled or framed based on the Style in the paint.
753 @param oval The rectangle bounds of the oval to be drawn
754 @param paint The paint used to draw the oval
756 virtual void drawOval(const SkRect& oval, const SkPaint&);
759 * Draw the specified RRect using the specified paint The rrect will be filled or stroked
760 * based on the Style in the paint.
762 * @param rrect The round-rect to draw
763 * @param paint The paint used to draw the round-rect
765 virtual void drawRRect(const SkRRect& rrect, const SkPaint& paint);
768 * Draw the annulus formed by the outer and inner rrects. The results
769 * are undefined if the outer does not contain the inner.
771 void drawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint&);
773 /** Draw the specified circle using the specified paint. If radius is <= 0,
774 then nothing will be drawn. The circle will be filled
775 or framed based on the Style in the paint.
776 @param cx The x-coordinate of the center of the cirle to be drawn
777 @param cy The y-coordinate of the center of the cirle to be drawn
778 @param radius The radius of the cirle to be drawn
779 @param paint The paint used to draw the circle
781 void drawCircle(SkScalar cx, SkScalar cy, SkScalar radius,
782 const SkPaint& paint);
784 /** Draw the specified arc, which will be scaled to fit inside the
785 specified oval. If the sweep angle is >= 360, then the oval is drawn
786 completely. Note that this differs slightly from SkPath::arcTo, which
787 treats the sweep angle mod 360.
788 @param oval The bounds of oval used to define the shape of the arc
789 @param startAngle Starting angle (in degrees) where the arc begins
790 @param sweepAngle Sweep angle (in degrees) measured clockwise
791 @param useCenter true means include the center of the oval. For filling
792 this will draw a wedge. False means just use the arc.
793 @param paint The paint used to draw the arc
795 void drawArc(const SkRect& oval, SkScalar startAngle, SkScalar sweepAngle,
796 bool useCenter, const SkPaint& paint);
798 /** Draw the specified round-rect using the specified paint. The round-rect
799 will be filled or framed based on the Style in the paint.
800 @param rect The rectangular bounds of the roundRect to be drawn
801 @param rx The x-radius of the oval used to round the corners
802 @param ry The y-radius of the oval used to round the corners
803 @param paint The paint used to draw the roundRect
805 void drawRoundRect(const SkRect& rect, SkScalar rx, SkScalar ry,
806 const SkPaint& paint);
808 /** Draw the specified path using the specified paint. The path will be
809 filled or framed based on the Style in the paint.
810 @param path The path to be drawn
811 @param paint The paint used to draw the path
813 virtual void drawPath(const SkPath& path, const SkPaint& paint);
815 virtual void drawImage(const SkImage* image, SkScalar left, SkScalar top,
816 const SkPaint* paint = NULL);
818 virtual void drawImageRect(const SkImage* image, const SkRect* src,
820 const SkPaint* paint = NULL);
822 /** Draw the specified bitmap, with its top/left corner at (x,y), using the
823 specified paint, transformed by the current matrix. Note: if the paint
824 contains a maskfilter that generates a mask which extends beyond the
825 bitmap's original width/height, then the bitmap will be drawn as if it
826 were in a Shader with CLAMP mode. Thus the color outside of the original
827 width/height will be the edge color replicated.
829 If a shader is present on the paint it will be ignored, except in the
830 case where the bitmap is kAlpha_8_SkColorType. In that case, the color is
831 generated by the shader.
833 @param bitmap The bitmap to be drawn
834 @param left The position of the left side of the bitmap being drawn
835 @param top The position of the top side of the bitmap being drawn
836 @param paint The paint used to draw the bitmap, or NULL
838 virtual void drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top,
839 const SkPaint* paint = NULL);
841 enum DrawBitmapRectFlags {
842 kNone_DrawBitmapRectFlag = 0x0,
844 * When filtering is enabled, allow the color samples outside of
845 * the src rect (but still in the src bitmap) to bleed into the
848 kBleed_DrawBitmapRectFlag = 0x1,
851 /** Draw the specified bitmap, with the specified matrix applied (before the
852 canvas' matrix is applied).
853 @param bitmap The bitmap to be drawn
854 @param src Optional: specify the subset of the bitmap to be drawn
855 @param dst The destination rectangle where the scaled/translated
857 @param paint The paint used to draw the bitmap, or NULL
859 virtual void drawBitmapRectToRect(const SkBitmap& bitmap, const SkRect* src,
861 const SkPaint* paint = NULL,
862 DrawBitmapRectFlags flags = kNone_DrawBitmapRectFlag);
864 void drawBitmapRect(const SkBitmap& bitmap, const SkRect& dst,
865 const SkPaint* paint = NULL) {
866 this->drawBitmapRectToRect(bitmap, NULL, dst, paint, kNone_DrawBitmapRectFlag);
869 void drawBitmapRect(const SkBitmap& bitmap, const SkIRect* isrc,
870 const SkRect& dst, const SkPaint* paint = NULL,
871 DrawBitmapRectFlags flags = kNone_DrawBitmapRectFlag) {
872 SkRect realSrcStorage;
873 SkRect* realSrcPtr = NULL;
875 realSrcStorage.set(*isrc);
876 realSrcPtr = &realSrcStorage;
878 this->drawBitmapRectToRect(bitmap, realSrcPtr, dst, paint, flags);
881 virtual void drawBitmapMatrix(const SkBitmap& bitmap, const SkMatrix& m,
882 const SkPaint* paint = NULL);
885 * Draw the bitmap stretched differentially to fit into dst.
886 * center is a rect within the bitmap, and logically divides the bitmap
887 * into 9 sections (3x3). For example, if the middle pixel of a [5x5]
888 * bitmap is the "center", then the center-rect should be [2, 2, 3, 3].
890 * If the dst is >= the bitmap size, then...
891 * - The 4 corners are not stretched at all.
892 * - The sides are stretched in only one axis.
893 * - The center is stretched in both axes.
894 * Else, for each axis where dst < bitmap,
895 * - The corners shrink proportionally
896 * - The sides (along the shrink axis) and center are not drawn
898 virtual void drawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
899 const SkRect& dst, const SkPaint* paint = NULL);
901 /** Draw the specified bitmap, with its top/left corner at (x,y),
902 NOT transformed by the current matrix. Note: if the paint
903 contains a maskfilter that generates a mask which extends beyond the
904 bitmap's original width/height, then the bitmap will be drawn as if it
905 were in a Shader with CLAMP mode. Thus the color outside of the original
906 width/height will be the edge color replicated.
907 @param bitmap The bitmap to be drawn
908 @param left The position of the left side of the bitmap being drawn
909 @param top The position of the top side of the bitmap being drawn
910 @param paint The paint used to draw the bitmap, or NULL
912 virtual void drawSprite(const SkBitmap& bitmap, int left, int top,
913 const SkPaint* paint = NULL);
915 /** Draw the text, with origin at (x,y), using the specified paint.
916 The origin is interpreted based on the Align setting in the paint.
917 @param text The text to be drawn
918 @param byteLength The number of bytes to read from the text parameter
919 @param x The x-coordinate of the origin of the text being drawn
920 @param y The y-coordinate of the origin of the text being drawn
921 @param paint The paint used for the text (e.g. color, size, style)
923 SK_LEGACY_DRAWTEXT_VIRTUAL void drawText(const void* text, size_t byteLength, SkScalar x,
924 SkScalar y, const SkPaint& paint);
926 /** Draw the text, with each character/glyph origin specified by the pos[]
927 array. The origin is interpreted by the Align setting in the paint.
928 @param text The text to be drawn
929 @param byteLength The number of bytes to read from the text parameter
930 @param pos Array of positions, used to position each character
931 @param paint The paint used for the text (e.g. color, size, style)
933 SK_LEGACY_DRAWTEXT_VIRTUAL void drawPosText(const void* text, size_t byteLength,
934 const SkPoint pos[], const SkPaint& paint);
936 /** Draw the text, with each character/glyph origin specified by the x
937 coordinate taken from the xpos[] array, and the y from the constY param.
938 The origin is interpreted by the Align setting in the paint.
939 @param text The text to be drawn
940 @param byteLength The number of bytes to read from the text parameter
941 @param xpos Array of x-positions, used to position each character
942 @param constY The shared Y coordinate for all of the positions
943 @param paint The paint used for the text (e.g. color, size, style)
945 SK_LEGACY_DRAWTEXT_VIRTUAL void drawPosTextH(const void* text, size_t byteLength,
946 const SkScalar xpos[], SkScalar constY,
947 const SkPaint& paint);
949 /** Draw the text, with origin at (x,y), using the specified paint, along
950 the specified path. The paint's Align setting determins where along the
951 path to start the text.
952 @param text The text to be drawn
953 @param byteLength The number of bytes to read from the text parameter
954 @param path The path the text should follow for its baseline
955 @param hOffset The distance along the path to add to the text's
957 @param vOffset The distance above(-) or below(+) the path to
959 @param paint The paint used for the text
961 void drawTextOnPathHV(const void* text, size_t byteLength,
962 const SkPath& path, SkScalar hOffset,
963 SkScalar vOffset, const SkPaint& paint);
965 /** Draw the text, with origin at (x,y), using the specified paint, along
966 the specified path. The paint's Align setting determins where along the
967 path to start the text.
968 @param text The text to be drawn
969 @param byteLength The number of bytes to read from the text parameter
970 @param path The path the text should follow for its baseline
971 @param matrix (may be null) Applied to the text before it is
973 @param paint The paint used for the text
975 SK_LEGACY_DRAWTEXT_VIRTUAL void drawTextOnPath(const void* text, size_t byteLength,
976 const SkPath& path, const SkMatrix* matrix,
977 const SkPaint& paint);
979 /** Draw the text blob, offset by (x,y), using the specified paint.
980 @param blob The text blob to be drawn
981 @param x The x-offset of the text being drawn
982 @param y The y-offset of the text being drawn
983 @param paint The paint used for the text (e.g. color, size, style)
985 void drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y, const SkPaint& paint);
987 /** PRIVATE / EXPERIMENTAL -- do not call
988 Perform back-end analysis/optimization of a picture. This may attach
989 optimization data to the picture which can be used by a later
991 @param picture The recorded drawing commands to analyze/optimize
993 void EXPERIMENTAL_optimize(const SkPicture* picture);
995 /** Draw the picture into this canvas. This method effective brackets the
996 playback of the picture's draw calls with save/restore, so the state
997 of this canvas will be unchanged after this call.
998 @param picture The recorded drawing commands to playback into this
1001 void drawPicture(const SkPicture* picture);
1004 * Draw the picture into this canvas.
1006 * If matrix is non-null, apply that matrix to the CTM when drawing this picture. This is
1007 * logically equivalent to
1008 * save/concat/drawPicture/restore
1010 * If paint is non-null, draw the picture into a temporary buffer, and then apply the paint's
1011 * alpha/colorfilter/imagefilter/xfermode to that buffer as it is drawn to the canvas.
1012 * This is logically equivalent to
1013 * saveLayer(paint)/drawPicture/restore
1015 void drawPicture(const SkPicture*, const SkMatrix* matrix, const SkPaint* paint);
1018 kTriangles_VertexMode,
1019 kTriangleStrip_VertexMode,
1020 kTriangleFan_VertexMode
1023 /** Draw the array of vertices, interpreted as triangles (based on mode).
1025 If both textures and vertex-colors are NULL, it strokes hairlines with
1026 the paint's color. This behavior is a useful debugging mode to visualize
1029 @param vmode How to interpret the array of vertices
1030 @param vertexCount The number of points in the vertices array (and
1031 corresponding texs and colors arrays if non-null)
1032 @param vertices Array of vertices for the mesh
1033 @param texs May be null. If not null, specifies the coordinate
1034 in _texture_ space (not uv space) for each vertex.
1035 @param colors May be null. If not null, specifies a color for each
1036 vertex, to be interpolated across the triangle.
1037 @param xmode Used if both texs and colors are present. In this
1038 case the colors are combined with the texture using mode,
1039 before being drawn using the paint. If mode is null, then
1040 kModulate_Mode is used.
1041 @param indices If not null, array of indices to reference into the
1042 vertex (texs, colors) array.
1043 @param indexCount number of entries in the indices array (if not null)
1044 @param paint Specifies the shader/texture if present.
1046 virtual void drawVertices(VertexMode vmode, int vertexCount,
1047 const SkPoint vertices[], const SkPoint texs[],
1048 const SkColor colors[], SkXfermode* xmode,
1049 const uint16_t indices[], int indexCount,
1050 const SkPaint& paint);
1053 Draw a cubic coons patch
1055 @param cubic specifies the 4 bounding cubic bezier curves of a patch with clockwise order
1056 starting at the top left corner.
1057 @param colors specifies the colors for the corners which will be bilerp across the patch,
1058 their order is clockwise starting at the top left corner.
1059 @param texCoords specifies the texture coordinates that will be bilerp across the patch,
1060 their order is the same as the colors.
1061 @param xmode specifies how are the colors and the textures combined if both of them are
1063 @param paint Specifies the shader/texture if present.
1065 void drawPatch(const SkPoint cubics[12], const SkColor colors[4],
1066 const SkPoint texCoords[4], SkXfermode* xmode, const SkPaint& paint);
1068 /** Send a blob of data to the canvas.
1069 For canvases that draw, this call is effectively a no-op, as the data
1070 is not parsed, but just ignored. However, this call exists for
1071 subclasses like SkPicture's recording canvas, that can store the data
1072 and then play it back later (via another call to drawData).
1074 virtual void drawData(const void* data, size_t length) {
1075 // do nothing. Subclasses may do something with the data
1078 /** Add comments. beginCommentGroup/endCommentGroup open/close a new group.
1079 Each comment added via addComment is notionally attached to its
1080 enclosing group. Top-level comments simply belong to no group.
1082 virtual void beginCommentGroup(const char* description) {
1083 // do nothing. Subclasses may do something
1085 virtual void addComment(const char* kywd, const char* value) {
1086 // do nothing. Subclasses may do something
1088 virtual void endCommentGroup() {
1089 // do nothing. Subclasses may do something
1093 * With this call the client asserts that subsequent draw operations (up to the
1094 * matching popCull()) are fully contained within the given bounding box. The assertion
1095 * is not enforced, but the information might be used to quick-reject command blocks,
1096 * so an incorrect bounding box may result in incomplete rendering.
1098 void pushCull(const SkRect& cullRect);
1101 * Terminates the current culling block, and restores the previous one (if any).
1105 //////////////////////////////////////////////////////////////////////////
1107 /** Get the current filter object. The filter's reference count is not
1108 affected. The filter is saved/restored, just like the matrix and clip.
1109 @return the canvas' filter (or NULL).
1111 SkDrawFilter* getDrawFilter() const;
1113 /** Set the new filter (or NULL). Pass NULL to clear any existing filter.
1114 As a convenience, the parameter is returned. If an existing filter
1115 exists, its refcnt is decrement. If the new filter is not null, its
1116 refcnt is incremented. The filter is saved/restored, just like the
1118 @param filter the new filter (or NULL)
1119 @return the new filter
1121 virtual SkDrawFilter* setDrawFilter(SkDrawFilter* filter);
1123 //////////////////////////////////////////////////////////////////////////
1126 * Return true if the current clip is empty (i.e. nothing will draw).
1127 * Note: this is not always a free call, so it should not be used
1128 * more often than necessary. However, once the canvas has computed this
1129 * result, subsequent calls will be cheap (until the clip state changes,
1130 * which can happen on any clip..() or restore() call.
1132 virtual bool isClipEmpty() const;
1135 * Returns true if the current clip is just a (non-empty) rectangle.
1136 * Returns false if the clip is empty, or if it is complex.
1138 virtual bool isClipRect() const;
1140 /** Return the current matrix on the canvas.
1141 This does not account for the translate in any of the devices.
1142 @return The current matrix on the canvas.
1144 const SkMatrix& getTotalMatrix() const;
1146 /** Return the clip stack. The clip stack stores all the individual
1147 * clips organized by the save/restore frame in which they were
1149 * @return the current clip stack ("list" of individual clip elements)
1151 const SkClipStack* getClipStack() const {
1155 typedef SkCanvasClipVisitor ClipVisitor;
1157 * Replays the clip operations, back to front, that have been applied to
1158 * the canvas, calling the appropriate method on the visitor for each
1159 * clip. All clips have already been transformed into device space.
1161 void replayClips(ClipVisitor*) const;
1163 ///////////////////////////////////////////////////////////////////////////
1165 /** After calling saveLayer(), there can be any number of devices that make
1166 up the top-most drawing area. LayerIter can be used to iterate through
1167 those devices. Note that the iterator is only valid until the next API
1168 call made on the canvas. Ownership of all pointers in the iterator stays
1169 with the canvas, so none of them should be modified or deleted.
1171 class SK_API LayerIter /*: SkNoncopyable*/ {
1173 /** Initialize iterator with canvas, and set values for 1st device */
1174 LayerIter(SkCanvas*, bool skipEmptyClips);
1177 /** Return true if the iterator is done */
1178 bool done() const { return fDone; }
1179 /** Cycle to the next device */
1182 // These reflect the current device in the iterator
1184 SkBaseDevice* device() const;
1185 const SkMatrix& matrix() const;
1186 const SkRegion& clip() const;
1187 const SkPaint& paint() const;
1192 // used to embed the SkDrawIter object directly in our instance, w/o
1193 // having to expose that class def to the public. There is an assert
1194 // in our constructor to ensure that fStorage is large enough
1195 // (though needs to be a compile-time-assert!). We use intptr_t to work
1196 // safely with 32 and 64 bit machines (to ensure the storage is enough)
1197 intptr_t fStorage[32];
1198 class SkDrawIter* fImpl; // this points at fStorage
1199 SkPaint fDefaultPaint;
1204 GrRenderTarget* internal_private_accessTopLayerRenderTarget();
1207 // default impl defers to getDevice()->newSurface(info)
1208 virtual SkSurface* onNewSurface(const SkImageInfo&, const SkSurfaceProps&);
1210 // default impl defers to its device
1211 virtual const void* onPeekPixels(SkImageInfo*, size_t* rowBytes);
1212 virtual void* onAccessTopLayerPixels(SkImageInfo*, size_t* rowBytes);
1214 // Subclass save/restore notifiers.
1215 // Overriders should call the corresponding INHERITED method up the inheritance chain.
1216 // willSaveLayer()'s return value may suppress full layer allocation.
1217 enum SaveLayerStrategy {
1218 kFullLayer_SaveLayerStrategy,
1219 kNoLayer_SaveLayerStrategy
1222 virtual void willSave() {}
1223 virtual SaveLayerStrategy willSaveLayer(const SkRect*, const SkPaint*, SaveFlags) {
1224 return kFullLayer_SaveLayerStrategy;
1226 virtual void willRestore() {}
1227 virtual void didRestore() {}
1228 virtual void didConcat(const SkMatrix&) {}
1229 virtual void didSetMatrix(const SkMatrix&) {}
1231 virtual void onDrawDRRect(const SkRRect&, const SkRRect&, const SkPaint&);
1233 virtual void onDrawText(const void* text, size_t byteLength, SkScalar x,
1234 SkScalar y, const SkPaint& paint);
1236 virtual void onDrawPosText(const void* text, size_t byteLength,
1237 const SkPoint pos[], const SkPaint& paint);
1239 virtual void onDrawPosTextH(const void* text, size_t byteLength,
1240 const SkScalar xpos[], SkScalar constY,
1241 const SkPaint& paint);
1243 virtual void onDrawTextOnPath(const void* text, size_t byteLength,
1244 const SkPath& path, const SkMatrix* matrix,
1245 const SkPaint& paint);
1247 virtual void onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
1248 const SkPaint& paint);
1250 virtual void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
1251 const SkPoint texCoords[4], SkXfermode* xmode, const SkPaint& paint);
1253 enum ClipEdgeStyle {
1254 kHard_ClipEdgeStyle,
1258 virtual void onClipRect(const SkRect& rect, SkRegion::Op op, ClipEdgeStyle edgeStyle);
1259 virtual void onClipRRect(const SkRRect& rrect, SkRegion::Op op, ClipEdgeStyle edgeStyle);
1260 virtual void onClipPath(const SkPath& path, SkRegion::Op op, ClipEdgeStyle edgeStyle);
1261 virtual void onClipRegion(const SkRegion& deviceRgn, SkRegion::Op op);
1263 virtual void onDiscard();
1265 virtual void onDrawPicture(const SkPicture*, const SkMatrix*, const SkPaint*);
1267 // Returns the canvas to be used by DrawIter. Default implementation
1268 // returns this. Subclasses that encapsulate an indirect canvas may
1269 // need to overload this method. The impl must keep track of this, as it
1270 // is not released or deleted by the caller.
1271 virtual SkCanvas* canvasForDrawIter();
1273 // Clip rectangle bounds. Called internally by saveLayer.
1274 // returns false if the entire rectangle is entirely clipped out
1275 // If non-NULL, The imageFilter parameter will be used to expand the clip
1276 // and offscreen bounds for any margin required by the filter DAG.
1277 bool clipRectBounds(const SkRect* bounds, SaveFlags flags,
1278 SkIRect* intersection,
1279 const SkImageFilter* imageFilter = NULL);
1281 // notify our surface (if we have one) that we are about to draw, so it
1282 // can perform copy-on-write or invalidate any cached images
1283 void predrawNotify();
1285 virtual void onPushCull(const SkRect& cullRect);
1286 virtual void onPopCull();
1291 SkClipStack fClipStack;
1293 // points to top of stack
1295 // the first N recs that can fit here mean we won't call malloc
1296 uint32_t fMCRecStorage[32];
1298 const SkSurfaceProps fProps;
1300 int fSaveLayerCount; // number of successful saveLayer calls
1301 int fCullCount; // number of active culls
1303 SkMetaData* fMetaData;
1305 SkSurface_Base* fSurfaceBase;
1306 SkSurface_Base* getSurfaceBase() const { return fSurfaceBase; }
1307 void setSurfaceBase(SkSurface_Base* sb) {
1310 friend class SkSurface_Base;
1311 friend class SkSurface_Gpu;
1313 bool fDeviceCMDirty; // cleared by updateDeviceCMCache()
1314 void updateDeviceCMCache();
1316 friend class SkDrawIter; // needs setupDrawForLayerDevice()
1317 friend class AutoDrawLooper;
1318 friend class SkLua; // needs top layer size and offset
1319 friend class SkDebugCanvas; // needs experimental fAllowSimplifyClip
1320 friend class SkDeferredDevice; // needs getTopDevice()
1321 friend class SkSurface_Raster; // needs getDevice()
1322 friend class SkRecorder; // InitFlags
1323 friend class SkNoSaveLayerCanvas; // InitFlags
1326 kDefault_InitFlags = 0,
1327 kConservativeRasterClip_InitFlag = 1 << 0,
1329 SkCanvas(int width, int height, InitFlags);
1330 SkCanvas(SkBaseDevice*, const SkSurfaceProps*, InitFlags);
1331 SkCanvas(const SkBitmap&, const SkSurfaceProps&);
1333 // needs gettotalclip()
1334 friend SkCanvasState* SkCanvasStateUtils::CaptureCanvasState(SkCanvas*);
1336 SkBaseDevice* createLayerDevice(const SkImageInfo&);
1338 // call this each time we attach ourselves to a device
1340 // - internalSaveLayer
1341 void setupDevice(SkBaseDevice*);
1343 SkBaseDevice* init(SkBaseDevice*, InitFlags);
1348 * Specify a device for this canvas to draw into. If it is not null, its
1349 * reference count is incremented. If the canvas was already holding a
1350 * device, its reference count is decremented. The new device is returned.
1352 SkBaseDevice* setRootDevice(SkBaseDevice* device);
1355 * Gets the size/origin of the top level layer in global canvas coordinates. We don't want this
1356 * to be public because it exposes decisions about layer sizes that are internal to the canvas.
1358 SkISize getTopLayerSize() const;
1359 SkIPoint getTopLayerOrigin() const;
1361 // internal methods are not virtual, so they can safely be called by other
1362 // canvas apis, without confusing subclasses (like SkPictureRecording)
1363 void internalDrawBitmap(const SkBitmap&, const SkMatrix& m, const SkPaint* paint);
1364 void internalDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src,
1365 const SkRect& dst, const SkPaint* paint,
1366 DrawBitmapRectFlags flags);
1367 void internalDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
1368 const SkRect& dst, const SkPaint* paint);
1369 void internalDrawPaint(const SkPaint& paint);
1370 int internalSaveLayer(const SkRect* bounds, const SkPaint* paint,
1371 SaveFlags, bool justForImageFilter, SaveLayerStrategy strategy);
1372 void internalDrawDevice(SkBaseDevice*, int x, int y, const SkPaint*);
1374 // shared by save() and saveLayer()
1376 void internalRestore();
1377 static void DrawRect(const SkDraw& draw, const SkPaint& paint,
1378 const SkRect& r, SkScalar textSize);
1379 static void DrawTextDecorations(const SkDraw& draw, const SkPaint& paint,
1380 const char text[], size_t byteLength,
1381 SkScalar x, SkScalar y);
1383 // only for canvasutils
1384 const SkRegion& internal_private_getTotalClip() const;
1386 /* These maintain a cache of the clip bounds in local coordinates,
1387 (converted to 2s-compliment if floats are slow).
1389 mutable SkRect fCachedLocalClipBounds;
1390 mutable bool fCachedLocalClipBoundsDirty;
1391 bool fAllowSoftClip;
1392 bool fAllowSimplifyClip;
1393 bool fConservativeRasterClip;
1395 const SkRect& getLocalClipBounds() const {
1396 if (fCachedLocalClipBoundsDirty) {
1397 if (!this->getClipBounds(&fCachedLocalClipBounds)) {
1398 fCachedLocalClipBounds.setEmpty();
1400 fCachedLocalClipBoundsDirty = false;
1402 return fCachedLocalClipBounds;
1405 class AutoValidateClip : ::SkNoncopyable {
1407 explicit AutoValidateClip(SkCanvas* canvas) : fCanvas(canvas) {
1408 fCanvas->validateClip();
1410 ~AutoValidateClip() { fCanvas->validateClip(); }
1413 const SkCanvas* fCanvas;
1417 // The cull stack rects are in device-space
1418 SkTDArray<SkIRect> fCullStack;
1419 void validateCull(const SkIRect&);
1420 void validateClip() const;
1422 void validateClip() const {}
1425 typedef SkRefCnt INHERITED;
1428 /** Stack helper class to automatically call restoreToCount() on the canvas
1429 when this object goes out of scope. Use this to guarantee that the canvas
1430 is restored to a known state.
1432 class SkAutoCanvasRestore : SkNoncopyable {
1434 SkAutoCanvasRestore(SkCanvas* canvas, bool doSave) : fCanvas(canvas), fSaveCount(0) {
1436 fSaveCount = canvas->getSaveCount();
1442 ~SkAutoCanvasRestore() {
1444 fCanvas->restoreToCount(fSaveCount);
1449 * Perform the restore now, instead of waiting for the destructor. Will
1450 * only do this once.
1454 fCanvas->restoreToCount(fSaveCount);
1463 #define SkAutoCanvasRestore(...) SK_REQUIRE_LOCAL_VAR(SkAutoCanvasRestore)
1465 /** Stack helper class to automatically open and close a comment block
1467 class SkAutoCommentBlock : SkNoncopyable {
1469 SkAutoCommentBlock(SkCanvas* canvas, const char* description) {
1472 fCanvas->beginCommentGroup(description);
1476 ~SkAutoCommentBlock() {
1478 fCanvas->endCommentGroup();
1485 #define SkAutoCommentBlock(...) SK_REQUIRE_LOCAL_VAR(SkAutoCommentBlock)
1488 * If the caller wants read-only access to the pixels in a canvas, it can just
1489 * call canvas->peekPixels(), since that is the fastest way to "peek" at the
1490 * pixels on a raster-backed canvas.
1492 * If the canvas has pixels, but they are not readily available to the CPU
1493 * (e.g. gpu-backed), then peekPixels() will fail, but readPixels() will
1494 * succeed (though be slower, since it will return a copy of the pixels).
1496 * SkAutoROCanvasPixels encapsulates these two techniques, trying first to call
1497 * peekPixels() (for performance), but if that fails, calling readPixels() and
1498 * storing the copy locally.
1500 * The caller must respect the restrictions associated with peekPixels(), since
1501 * that may have been called: The returned information is invalidated if...
1502 * - any API is called on the canvas (or its parent surface if present)
1503 * - the canvas goes out of scope
1505 class SkAutoROCanvasPixels : SkNoncopyable {
1507 SkAutoROCanvasPixels(SkCanvas* canvas);
1509 // returns NULL on failure
1510 const void* addr() const { return fAddr; }
1512 // undefined if addr() == NULL
1513 size_t rowBytes() const { return fRowBytes; }
1515 // undefined if addr() == NULL
1516 const SkImageInfo& info() const { return fInfo; }
1518 // helper that, if returns true, installs the pixels into the bitmap. Note
1519 // that the bitmap may reference the address returned by peekPixels(), so
1520 // the caller must respect the restrictions associated with peekPixels().
1521 bool asROBitmap(SkBitmap*) const;
1524 SkBitmap fBitmap; // used if peekPixels() fails
1525 const void* fAddr; // NULL on failure
1530 static inline SkCanvas::SaveFlags operator|(const SkCanvas::SaveFlags lhs,
1531 const SkCanvas::SaveFlags rhs) {
1532 return static_cast<SkCanvas::SaveFlags>(static_cast<int>(lhs) | static_cast<int>(rhs));
1535 static inline SkCanvas::SaveFlags& operator|=(SkCanvas::SaveFlags& lhs,
1536 const SkCanvas::SaveFlags rhs) {
1541 class SkCanvasClipVisitor {
1543 virtual ~SkCanvasClipVisitor();
1544 virtual void clipRect(const SkRect&, SkRegion::Op, bool antialias) = 0;
1545 virtual void clipRRect(const SkRRect&, SkRegion::Op, bool antialias) = 0;
1546 virtual void clipPath(const SkPath&, SkRegion::Op, bool antialias) = 0;