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 "SkXfermode.h"
34 A Canvas encapsulates all of the state about drawing into a device (bitmap).
35 This includes a reference to the device itself, and a stack of matrix/clip
36 values. For any given draw call (e.g. drawRect), the geometry of the object
37 being drawn is transformed by the concatenation of all the matrices in the
38 stack. The transformed geometry is clipped by the intersection of all of
39 the clips in the stack.
41 While the Canvas holds the state of the drawing device, the state (style)
42 of the object being drawn is held by the Paint, which is provided as a
43 parameter to each of the draw() methods. The Paint holds attributes such as
44 color, typeface, textSize, strokeWidth, shader (e.g. gradients, patterns),
47 class SK_API SkCanvas : public SkRefCnt {
49 SK_DECLARE_INST_COUNT(SkCanvas)
52 * Creates an empty canvas with no backing device/pixels, and zero
58 * Creates a canvas of the specified dimensions, but explicitly not backed
59 * by any device/pixels. Typically this use used by subclasses who handle
60 * the draw calls in some other way.
62 SkCanvas(int width, int height);
64 /** Construct a canvas with the specified device to draw into.
66 @param device Specifies a device for the canvas to draw into.
68 explicit SkCanvas(SkBaseDevice* device);
70 /** Construct a canvas with the specified bitmap to draw into.
71 @param bitmap Specifies a bitmap for the canvas to draw into. Its
72 structure are copied to the canvas.
74 explicit SkCanvas(const SkBitmap& bitmap);
77 SkMetaData& getMetaData();
80 * Return ImageInfo for this canvas. If the canvas is not backed by pixels
81 * (cpu or gpu), then the info's ColorType will be kUnknown_SkColorType.
83 SkImageInfo imageInfo() const;
85 ///////////////////////////////////////////////////////////////////////////
88 * Trigger the immediate execution of all pending draw operations.
93 * DEPRECATED: call imageInfo() instead.
94 * Return the width/height of the underlying device. The current drawable
95 * area may be small (due to clipping or saveLayer). For a canvas with
96 * no device, 0,0 will be returned.
98 SkISize getDeviceSize() const;
102 * Return the canvas' device object, which may be null. The device holds
103 * the bitmap of the pixels that the canvas draws into. The reference count
104 * of the returned device is not changed by this call.
106 SkBaseDevice* getDevice() const;
109 * saveLayer() can create another device (which is later drawn onto
110 * the previous device). getTopDevice() returns the top-most device current
111 * installed. Note that this can change on other calls like save/restore,
112 * so do not access this device after subsequent canvas calls.
113 * The reference count of the device is not changed.
115 * @param updateMatrixClip If this is true, then before the device is
116 * returned, we ensure that its has been notified about the current
117 * matrix and clip. Note: this happens automatically when the device
118 * is drawn to, but is optional here, as there is a small perf hit
121 SkBaseDevice* getTopDevice(bool updateMatrixClip = false) const;
124 * Create a new surface matching the specified info, one that attempts to
125 * be maximally compatible when used with this canvas.
127 SkSurface* newSurface(const SkImageInfo&);
130 * Return the GPU context of the device that is associated with the canvas.
131 * For a canvas with non-GPU device, NULL is returned.
133 GrContext* getGrContext();
135 ///////////////////////////////////////////////////////////////////////////
138 * If the canvas has pixels (and is not recording to a picture or other
139 * non-raster target) and has direct access to its pixels (i.e. they are in
140 * local RAM) return the const-address of those pixels, and if not null,
141 * return the ImageInfo and rowBytes. The returned address is only valid
142 * while the canvas object is in scope and unchanged. Any API calls made on
143 * canvas (or its parent surface if any) will invalidate the
144 * returned address (and associated information).
146 * On failure, returns NULL and the info and rowBytes parameters are
149 const void* peekPixels(SkImageInfo* info, size_t* rowBytes);
152 * This enum can be used with read/writePixels to perform a pixel ops to or
153 * from an 8888 config other than Skia's native config (SkPMColor). There
154 * are three byte orders supported: native, BGRA, and RGBA. Each has a
155 * premultiplied and unpremultiplied variant.
157 * Components of a 8888 pixel can be packed/unpacked from a 32bit word using
158 * either byte offsets or shift values. Byte offsets are endian-invariant
159 * while shifts are not. BGRA and RGBA configs are defined by byte
160 * orderings. The native config is defined by shift values (SK_A32_SHIFT,
161 * ..., SK_B32_SHIFT).
165 * Skia's native order specified by:
166 * SK_A32_SHIFT, SK_R32_SHIFT, SK_G32_SHIFT, and SK_B32_SHIFT
168 * kNative_Premul_Config8888 is equivalent to SkPMColor
169 * kNative_Unpremul_Config8888 has the same component order as SkPMColor
170 * but is not premultiplied.
172 kNative_Premul_Config8888,
173 kNative_Unpremul_Config8888,
175 * low byte to high byte: B, G, R, A.
177 kBGRA_Premul_Config8888,
178 kBGRA_Unpremul_Config8888,
180 * low byte to high byte: R, G, B, A.
182 kRGBA_Premul_Config8888,
183 kRGBA_Unpremul_Config8888
187 * On success (returns true), copy the canvas pixels into the bitmap.
188 * On failure, the bitmap parameter is left unchanged and false is
191 * The canvas' pixels are converted to the bitmap's config. The only
192 * supported config is kARGB_8888_Config, though this is likely to be
193 * relaxed in the future. The meaning of config kARGB_8888_Config is
194 * modified by the enum param config8888. The default value interprets
195 * kARGB_8888_Config as SkPMColor
197 * If the bitmap has pixels already allocated, the canvas pixels will be
198 * written there. If not, bitmap->allocPixels() will be called
199 * automatically. If the bitmap is backed by a texture readPixels will
202 * The actual pixels written is the intersection of the canvas' bounds, and
203 * the rectangle formed by the bitmap's width,height and the specified x,y.
204 * If bitmap pixels extend outside of that intersection, they will not be
207 * Other failure conditions:
208 * * If the canvas is backed by a non-raster device (e.g. PDF) then
209 * readPixels will fail.
210 * * If bitmap is texture-backed then readPixels will fail. (This may be
211 * relaxed in the future.)
213 * Example that reads the entire canvas into a bitmap using the native
215 * SkISize size = canvas->getDeviceSize();
216 * bitmap->setConfig(SkBitmap::kARGB_8888_Config, size.fWidth,
218 * if (canvas->readPixels(bitmap, 0, 0)) {
222 bool readPixels(SkBitmap* bitmap,
224 Config8888 config8888 = kNative_Premul_Config8888);
227 * DEPRECATED: This will be removed as soon as webkit is no longer relying
228 * on it. The bitmap is resized to the intersection of srcRect and the
229 * canvas bounds. New pixels are always allocated on success. Bitmap is
230 * unmodified on failure.
232 bool readPixels(const SkIRect& srcRect, SkBitmap* bitmap);
235 * Similar to draw sprite, this method will copy the pixels in bitmap onto
236 * the canvas, with the top/left corner specified by (x, y). The canvas'
237 * pixel values are completely replaced: there is no blending.
239 * Currently if bitmap is backed by a texture this is a no-op. This may be
240 * relaxed in the future.
242 * If the bitmap has config kARGB_8888_Config then the config8888 param
243 * will determines how the pixel valuess are intepreted. If the bitmap is
244 * not kARGB_8888_Config then this parameter is ignored.
246 * Note: If you are recording drawing commands on this canvas to
247 * SkPicture, writePixels() is ignored!
249 void writePixels(const SkBitmap& bitmap,
251 Config8888 config8888 = kNative_Premul_Config8888);
253 ///////////////////////////////////////////////////////////////////////////
256 /** save the matrix state, restoring it on restore() */
257 kMatrix_SaveFlag = 0x01,
258 /** save the clip state, restoring it on restore() */
259 kClip_SaveFlag = 0x02,
260 /** the layer needs to support per-pixel alpha */
261 kHasAlphaLayer_SaveFlag = 0x04,
262 /** the layer needs to support 8-bits per color component */
263 kFullColorLayer_SaveFlag = 0x08,
264 /** the layer should clip against the bounds argument */
265 kClipToLayer_SaveFlag = 0x10,
267 // helper masks for common choices
268 kMatrixClip_SaveFlag = 0x03,
269 kARGB_NoClipLayer_SaveFlag = 0x0F,
270 kARGB_ClipLayer_SaveFlag = 0x1F
273 /** This call saves the current matrix, clip, and drawFilter, and pushes a
274 copy onto a private stack. Subsequent calls to translate, scale,
275 rotate, skew, concat or clipRect, clipPath, and setDrawFilter all
276 operate on this copy.
277 When the balancing call to restore() is made, the previous matrix, clip,
278 and drawFilter are restored.
279 @param flags The flags govern what portion of the Matrix/Clip/drawFilter
280 state the save (and matching restore) effect. For example,
281 if only kMatrix is specified, then only the matrix state
282 will be pushed and popped. Likewise for the clip if kClip
283 is specified. However, the drawFilter is always affected
284 by calls to save/restore.
285 @return The value to pass to restoreToCount() to balance this save()
287 virtual int save(SaveFlags flags = kMatrixClip_SaveFlag);
289 /** This behaves the same as save(), but in addition it allocates an
290 offscreen bitmap. All drawing calls are directed there, and only when
291 the balancing call to restore() is made is that offscreen transfered to
292 the canvas (or the previous layer).
293 @param bounds (may be null) This rect, if non-null, is used as a hint to
294 limit the size of the offscreen, and thus drawing may be
295 clipped to it, though that clipping is not guaranteed to
296 happen. If exact clipping is desired, use clipRect().
297 @param paint (may be null) This is copied, and is applied to the
298 offscreen when restore() is called
299 @param flags LayerFlags
300 @return The value to pass to restoreToCount() to balance this save()
302 virtual int saveLayer(const SkRect* bounds, const SkPaint* paint,
303 SaveFlags flags = kARGB_ClipLayer_SaveFlag);
305 /** This behaves the same as save(), but in addition it allocates an
306 offscreen bitmap. All drawing calls are directed there, and only when
307 the balancing call to restore() is made is that offscreen transfered to
308 the canvas (or the previous layer).
309 @param bounds (may be null) This rect, if non-null, is used as a hint to
310 limit the size of the offscreen, and thus drawing may be
311 clipped to it, though that clipping is not guaranteed to
312 happen. If exact clipping is desired, use clipRect().
313 @param alpha This is applied to the offscreen when restore() is called.
314 @param flags LayerFlags
315 @return The value to pass to restoreToCount() to balance this save()
317 int saveLayerAlpha(const SkRect* bounds, U8CPU alpha,
318 SaveFlags flags = kARGB_ClipLayer_SaveFlag);
320 /** This call balances a previous call to save(), and is used to remove all
321 modifications to the matrix/clip/drawFilter state since the last save
323 It is an error to call restore() more times than save() was called.
325 virtual void restore();
327 /** Returns the number of matrix/clip states on the SkCanvas' private stack.
328 This will equal # save() calls - # restore() calls + 1. The save count on
331 int getSaveCount() const;
333 /** Efficient way to pop any calls to save() that happened after the save
334 count reached saveCount. It is an error for saveCount to be greater than
335 getSaveCount(). To pop all the way back to the initial matrix/clip context
337 @param saveCount The number of save() levels to restore from
339 void restoreToCount(int saveCount);
341 /** Returns true if drawing is currently going to a layer (from saveLayer)
342 * rather than to the root device.
344 virtual bool isDrawingToLayer() const;
346 /** Preconcat the current matrix with the specified translation
347 @param dx The distance to translate in X
348 @param dy The distance to translate in Y
349 returns true if the operation succeeded (e.g. did not overflow)
351 virtual bool translate(SkScalar dx, SkScalar dy);
353 /** Preconcat the current matrix with the specified scale.
354 @param sx The amount to scale in X
355 @param sy The amount to scale in Y
356 returns true if the operation succeeded (e.g. did not overflow)
358 virtual bool scale(SkScalar sx, SkScalar sy);
360 /** Preconcat the current matrix with the specified rotation.
361 @param degrees The amount to rotate, in degrees
362 returns true if the operation succeeded (e.g. did not overflow)
364 virtual bool rotate(SkScalar degrees);
366 /** Preconcat the current matrix with the specified skew.
367 @param sx The amount to skew in X
368 @param sy The amount to skew in Y
369 returns true if the operation succeeded (e.g. did not overflow)
371 virtual bool skew(SkScalar sx, SkScalar sy);
373 /** Preconcat the current matrix with the specified matrix.
374 @param matrix The matrix to preconcatenate with the current matrix
375 @return true if the operation succeeded (e.g. did not overflow)
377 virtual bool concat(const SkMatrix& matrix);
379 /** Replace the current matrix with a copy of the specified matrix.
380 @param matrix The matrix that will be copied into the current matrix.
382 virtual void setMatrix(const SkMatrix& matrix);
384 /** Helper for setMatrix(identity). Sets the current matrix to identity.
389 * Modify the current clip with the specified rectangle.
390 * @param rect The rect to combine with the current clip
391 * @param op The region op to apply to the current clip
392 * @param doAntiAlias true if the clip should be antialiased
393 * @return true if the canvas' clip is non-empty
395 virtual bool clipRect(const SkRect& rect,
396 SkRegion::Op op = SkRegion::kIntersect_Op,
397 bool doAntiAlias = false);
400 * Modify the current clip with the specified SkRRect.
401 * @param rrect The rrect to combine with the current clip
402 * @param op The region op to apply to the current clip
403 * @param doAntiAlias true if the clip should be antialiased
404 * @return true if the canvas' clip is non-empty
406 virtual bool clipRRect(const SkRRect& rrect,
407 SkRegion::Op op = SkRegion::kIntersect_Op,
408 bool doAntiAlias = false);
411 * Modify the current clip with the specified path.
412 * @param path The path to combine with the current clip
413 * @param op The region op to apply to the current clip
414 * @param doAntiAlias true if the clip should be antialiased
415 * @return true if the canvas' new clip is non-empty
417 virtual bool clipPath(const SkPath& path,
418 SkRegion::Op op = SkRegion::kIntersect_Op,
419 bool doAntiAlias = false);
421 /** EXPERIMENTAL -- only used for testing
422 Set to false to force clips to be hard, even if doAntiAlias=true is
423 passed to clipRect or clipPath.
425 void setAllowSoftClip(bool allow) {
426 fAllowSoftClip = allow;
429 /** EXPERIMENTAL -- only used for testing
430 Set to simplify clip stack using path ops.
432 void setAllowSimplifyClip(bool allow) {
433 fAllowSimplifyClip = allow;
436 /** Modify the current clip with the specified region. Note that unlike
437 clipRect() and clipPath() which transform their arguments by the current
438 matrix, clipRegion() assumes its argument is already in device
439 coordinates, and so no transformation is performed.
440 @param deviceRgn The region to apply to the current clip
441 @param op The region op to apply to the current clip
442 @return true if the canvas' new clip is non-empty
444 virtual bool clipRegion(const SkRegion& deviceRgn,
445 SkRegion::Op op = SkRegion::kIntersect_Op);
447 /** Helper for clipRegion(rgn, kReplace_Op). Sets the current clip to the
448 specified region. This does not intersect or in any other way account
449 for the existing clip region.
450 @param deviceRgn The region to copy into the current clip.
451 @return true if the new clip region is non-empty
453 bool setClipRegion(const SkRegion& deviceRgn) {
454 return this->clipRegion(deviceRgn, SkRegion::kReplace_Op);
457 /** Return true if the specified rectangle, after being transformed by the
458 current matrix, would lie completely outside of the current clip. Call
459 this to check if an area you intend to draw into is clipped out (and
460 therefore you can skip making the draw calls).
461 @param rect the rect to compare with the current clip
462 @return true if the rect (transformed by the canvas' matrix) does not
463 intersect with the canvas' clip
465 bool quickReject(const SkRect& rect) const;
467 /** Return true if the specified path, after being transformed by the
468 current matrix, would lie completely outside of the current clip. Call
469 this to check if an area you intend to draw into is clipped out (and
470 therefore you can skip making the draw calls). Note, for speed it may
471 return false even if the path itself might not intersect the clip
472 (i.e. the bounds of the path intersects, but the path does not).
473 @param path The path to compare with the current clip
474 @return true if the path (transformed by the canvas' matrix) does not
475 intersect with the canvas' clip
477 bool quickReject(const SkPath& path) const;
479 /** Return true if the horizontal band specified by top and bottom is
480 completely clipped out. This is a conservative calculation, meaning
481 that it is possible that if the method returns false, the band may still
482 in fact be clipped out, but the converse is not true. If this method
483 returns true, then the band is guaranteed to be clipped out.
484 @param top The top of the horizontal band to compare with the clip
485 @param bottom The bottom of the horizontal and to compare with the clip
486 @return true if the horizontal band is completely clipped out (i.e. does
487 not intersect the current clip)
489 bool quickRejectY(SkScalar top, SkScalar bottom) const {
490 SkASSERT(top <= bottom);
491 const SkRect& clipR = this->getLocalClipBounds();
492 // In the case where the clip is empty and we are provided with a
493 // negative top and positive bottom parameter then this test will return
494 // false even though it will be clipped. We have chosen to exclude that
495 // check as it is rare and would result double the comparisons.
496 return top >= clipR.fBottom || bottom <= clipR.fTop;
499 /** Return the bounds of the current clip (in local coordinates) in the
500 bounds parameter, and return true if it is non-empty. This can be useful
501 in a way similar to quickReject, in that it tells you that drawing
502 outside of these bounds will be clipped out.
504 bool getClipBounds(SkRect* bounds) const;
506 /** Return the bounds of the current clip, in device coordinates; returns
507 true if non-empty. Maybe faster than getting the clip explicitly and
508 then taking its bounds.
510 bool getClipDeviceBounds(SkIRect* bounds) const;
513 /** Fill the entire canvas' bitmap (restricted to the current clip) with the
514 specified ARGB color, using the specified mode.
515 @param a the alpha component (0..255) of the color to fill the canvas
516 @param r the red component (0..255) of the color to fill the canvas
517 @param g the green component (0..255) of the color to fill the canvas
518 @param b the blue component (0..255) of the color to fill the canvas
519 @param mode the mode to apply the color in (defaults to SrcOver)
521 void drawARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b,
522 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode);
524 /** Fill the entire canvas' bitmap (restricted to the current clip) with the
525 specified color and mode.
526 @param color the color to draw with
527 @param mode the mode to apply the color in (defaults to SrcOver)
529 void drawColor(SkColor color,
530 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode);
533 * This erases the entire drawing surface to the specified color,
534 * irrespective of the clip. It does not blend with the previous pixels,
535 * but always overwrites them.
537 * It is roughly equivalent to the following:
539 * canvas.clipRect(hugeRect, kReplace_Op);
540 * paint.setColor(color);
541 * paint.setXfermodeMode(kSrc_Mode);
542 * canvas.drawPaint(paint);
544 * though it is almost always much more efficient.
546 virtual void clear(SkColor);
549 * Fill the entire canvas' bitmap (restricted to the current clip) with the
551 * @param paint The paint used to fill the canvas
553 virtual void drawPaint(const SkPaint& paint);
556 /** drawPoints draws each point separately */
558 /** drawPoints draws each pair of points as a line segment */
560 /** drawPoints draws the array of points as a polygon */
564 /** Draw a series of points, interpreted based on the PointMode mode. For
565 all modes, the count parameter is interpreted as the total number of
566 points. For kLine mode, count/2 line segments are drawn.
567 For kPoint mode, each point is drawn centered at its coordinate, and its
568 size is specified by the paint's stroke-width. It draws as a square,
569 unless the paint's cap-type is round, in which the points are drawn as
571 For kLine mode, each pair of points is drawn as a line segment,
572 respecting the paint's settings for cap/join/width.
573 For kPolygon mode, the entire array is drawn as a series of connected
575 Note that, while similar, kLine and kPolygon modes draw slightly
576 differently than the equivalent path built with a series of moveto,
577 lineto calls, in that the path will draw all of its contours at once,
578 with no interactions if contours intersect each other (think XOR
579 xfermode). drawPoints always draws each element one at a time.
580 @param mode PointMode specifying how to draw the array of points.
581 @param count The number of points in the array
582 @param pts Array of points to draw
583 @param paint The paint used to draw the points
585 virtual void drawPoints(PointMode mode, size_t count, const SkPoint pts[],
586 const SkPaint& paint);
588 /** Helper method for drawing a single point. See drawPoints() for a more
591 void drawPoint(SkScalar x, SkScalar y, const SkPaint& paint);
593 /** Draws a single pixel in the specified color.
594 @param x The X coordinate of which pixel to draw
595 @param y The Y coordiante of which pixel to draw
596 @param color The color to draw
598 void drawPoint(SkScalar x, SkScalar y, SkColor color);
600 /** Draw a line segment with the specified start and stop x,y coordinates,
601 using the specified paint. NOTE: since a line is always "framed", the
602 paint's Style is ignored.
603 @param x0 The x-coordinate of the start point of the line
604 @param y0 The y-coordinate of the start point of the line
605 @param x1 The x-coordinate of the end point of the line
606 @param y1 The y-coordinate of the end point of the line
607 @param paint The paint used to draw the line
609 void drawLine(SkScalar x0, SkScalar y0, SkScalar x1, SkScalar y1,
610 const SkPaint& paint);
612 /** Draw the specified rectangle using the specified paint. The rectangle
613 will be filled or stroked based on the Style in the paint.
614 @param rect The rect to be drawn
615 @param paint The paint used to draw the rect
617 virtual void drawRect(const SkRect& rect, const SkPaint& paint);
619 /** Draw the specified rectangle using the specified paint. The rectangle
620 will be filled or framed based on the Style in the paint.
621 @param rect The rect to be drawn
622 @param paint The paint used to draw the rect
624 void drawIRect(const SkIRect& rect, const SkPaint& paint)
627 r.set(rect); // promotes the ints to scalars
628 this->drawRect(r, paint);
631 /** Draw the specified rectangle using the specified paint. The rectangle
632 will be filled or framed based on the Style in the paint.
633 @param left The left side of the rectangle to be drawn
634 @param top The top side of the rectangle to be drawn
635 @param right The right side of the rectangle to be drawn
636 @param bottom The bottom side of the rectangle to be drawn
637 @param paint The paint used to draw the rect
639 void drawRectCoords(SkScalar left, SkScalar top, SkScalar right,
640 SkScalar bottom, const SkPaint& paint);
642 /** Draw the specified oval using the specified paint. The oval will be
643 filled or framed based on the Style in the paint.
644 @param oval The rectangle bounds of the oval to be drawn
645 @param paint The paint used to draw the oval
647 virtual void drawOval(const SkRect& oval, const SkPaint&);
650 * Draw the specified RRect using the specified paint The rrect will be filled or stroked
651 * based on the Style in the paint.
653 * @param rrect The round-rect to draw
654 * @param paint The paint used to draw the round-rect
656 virtual void drawRRect(const SkRRect& rrect, const SkPaint& paint);
658 /** Draw the specified circle using the specified paint. If radius is <= 0,
659 then nothing will be drawn. The circle will be filled
660 or framed based on the Style in the paint.
661 @param cx The x-coordinate of the center of the cirle to be drawn
662 @param cy The y-coordinate of the center of the cirle to be drawn
663 @param radius The radius of the cirle to be drawn
664 @param paint The paint used to draw the circle
666 void drawCircle(SkScalar cx, SkScalar cy, SkScalar radius,
667 const SkPaint& paint);
669 /** Draw the specified arc, which will be scaled to fit inside the
670 specified oval. If the sweep angle is >= 360, then the oval is drawn
671 completely. Note that this differs slightly from SkPath::arcTo, which
672 treats the sweep angle mod 360.
673 @param oval The bounds of oval used to define the shape of the arc
674 @param startAngle Starting angle (in degrees) where the arc begins
675 @param sweepAngle Sweep angle (in degrees) measured clockwise
676 @param useCenter true means include the center of the oval. For filling
677 this will draw a wedge. False means just use the arc.
678 @param paint The paint used to draw the arc
680 void drawArc(const SkRect& oval, SkScalar startAngle, SkScalar sweepAngle,
681 bool useCenter, const SkPaint& paint);
683 /** Draw the specified round-rect using the specified paint. The round-rect
684 will be filled or framed based on the Style in the paint.
685 @param rect The rectangular bounds of the roundRect to be drawn
686 @param rx The x-radius of the oval used to round the corners
687 @param ry The y-radius of the oval used to round the corners
688 @param paint The paint used to draw the roundRect
690 void drawRoundRect(const SkRect& rect, SkScalar rx, SkScalar ry,
691 const SkPaint& paint);
693 /** Draw the specified path using the specified paint. The path will be
694 filled or framed based on the Style in the paint.
695 @param path The path to be drawn
696 @param paint The paint used to draw the path
698 virtual void drawPath(const SkPath& path, const SkPaint& paint);
700 /** Draw the specified bitmap, with its top/left corner at (x,y), using the
701 specified paint, transformed by the current matrix. Note: if the paint
702 contains a maskfilter that generates a mask which extends beyond the
703 bitmap's original width/height, then the bitmap will be drawn as if it
704 were in a Shader with CLAMP mode. Thus the color outside of the original
705 width/height will be the edge color replicated.
707 If a shader is present on the paint it will be ignored, except in the
708 case where the bitmap is kA8_Config. In that case, the color is
709 generated by the shader.
711 @param bitmap The bitmap to be drawn
712 @param left The position of the left side of the bitmap being drawn
713 @param top The position of the top side of the bitmap being drawn
714 @param paint The paint used to draw the bitmap, or NULL
716 virtual void drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top,
717 const SkPaint* paint = NULL);
719 enum DrawBitmapRectFlags {
720 kNone_DrawBitmapRectFlag = 0x0,
722 * When filtering is enabled, allow the color samples outside of
723 * the src rect (but still in the src bitmap) to bleed into the
726 kBleed_DrawBitmapRectFlag = 0x1,
729 /** Draw the specified bitmap, with the specified matrix applied (before the
730 canvas' matrix is applied).
731 @param bitmap The bitmap to be drawn
732 @param src Optional: specify the subset of the bitmap to be drawn
733 @param dst The destination rectangle where the scaled/translated
735 @param paint The paint used to draw the bitmap, or NULL
737 virtual void drawBitmapRectToRect(const SkBitmap& bitmap, const SkRect* src,
739 const SkPaint* paint = NULL,
740 DrawBitmapRectFlags flags = kNone_DrawBitmapRectFlag);
742 void drawBitmapRect(const SkBitmap& bitmap, const SkRect& dst,
743 const SkPaint* paint = NULL) {
744 this->drawBitmapRectToRect(bitmap, NULL, dst, paint, kNone_DrawBitmapRectFlag);
747 void drawBitmapRect(const SkBitmap& bitmap, const SkIRect* isrc,
748 const SkRect& dst, const SkPaint* paint = NULL,
749 DrawBitmapRectFlags flags = kNone_DrawBitmapRectFlag) {
750 SkRect realSrcStorage;
751 SkRect* realSrcPtr = NULL;
753 realSrcStorage.set(*isrc);
754 realSrcPtr = &realSrcStorage;
756 this->drawBitmapRectToRect(bitmap, realSrcPtr, dst, paint, flags);
759 virtual void drawBitmapMatrix(const SkBitmap& bitmap, const SkMatrix& m,
760 const SkPaint* paint = NULL);
763 * Draw the bitmap stretched differentially to fit into dst.
764 * center is a rect within the bitmap, and logically divides the bitmap
765 * into 9 sections (3x3). For example, if the middle pixel of a [5x5]
766 * bitmap is the "center", then the center-rect should be [2, 2, 3, 3].
768 * If the dst is >= the bitmap size, then...
769 * - The 4 corners are not stretched at all.
770 * - The sides are stretched in only one axis.
771 * - The center is stretched in both axes.
772 * Else, for each axis where dst < bitmap,
773 * - The corners shrink proportionally
774 * - The sides (along the shrink axis) and center are not drawn
776 virtual void drawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
777 const SkRect& dst, const SkPaint* paint = NULL);
779 /** Draw the specified bitmap, with its top/left corner at (x,y),
780 NOT transformed by the current matrix. Note: if the paint
781 contains a maskfilter that generates a mask which extends beyond the
782 bitmap's original width/height, then the bitmap will be drawn as if it
783 were in a Shader with CLAMP mode. Thus the color outside of the original
784 width/height will be the edge color replicated.
785 @param bitmap The bitmap to be drawn
786 @param left The position of the left side of the bitmap being drawn
787 @param top The position of the top side of the bitmap being drawn
788 @param paint The paint used to draw the bitmap, or NULL
790 virtual void drawSprite(const SkBitmap& bitmap, int left, int top,
791 const SkPaint* paint = NULL);
793 /** Draw the text, with origin at (x,y), using the specified paint.
794 The origin is interpreted based on the Align setting in the paint.
795 @param text The text to be drawn
796 @param byteLength The number of bytes to read from the text parameter
797 @param x The x-coordinate of the origin of the text being drawn
798 @param y The y-coordinate of the origin of the text being drawn
799 @param paint The paint used for the text (e.g. color, size, style)
801 virtual void drawText(const void* text, size_t byteLength, SkScalar x,
802 SkScalar y, const SkPaint& paint);
804 /** Draw the text, with each character/glyph origin specified by the pos[]
805 array. The origin is interpreted by the Align setting in the paint.
806 @param text The text to be drawn
807 @param byteLength The number of bytes to read from the text parameter
808 @param pos Array of positions, used to position each character
809 @param paint The paint used for the text (e.g. color, size, style)
811 virtual void drawPosText(const void* text, size_t byteLength,
812 const SkPoint pos[], const SkPaint& paint);
814 /** Draw the text, with each character/glyph origin specified by the x
815 coordinate taken from the xpos[] array, and the y from the constY param.
816 The origin is interpreted by the Align setting in the paint.
817 @param text The text to be drawn
818 @param byteLength The number of bytes to read from the text parameter
819 @param xpos Array of x-positions, used to position each character
820 @param constY The shared Y coordinate for all of the positions
821 @param paint The paint used for the text (e.g. color, size, style)
823 virtual void drawPosTextH(const void* text, size_t byteLength,
824 const SkScalar xpos[], SkScalar constY,
825 const SkPaint& paint);
827 /** Draw the text, with origin at (x,y), using the specified paint, along
828 the specified path. The paint's Align setting determins where along the
829 path to start the text.
830 @param text The text to be drawn
831 @param byteLength The number of bytes to read from the text parameter
832 @param path The path the text should follow for its baseline
833 @param hOffset The distance along the path to add to the text's
835 @param vOffset The distance above(-) or below(+) the path to
837 @param paint The paint used for the text
839 void drawTextOnPathHV(const void* text, size_t byteLength,
840 const SkPath& path, SkScalar hOffset,
841 SkScalar vOffset, const SkPaint& paint);
843 /** Draw the text, with origin at (x,y), using the specified paint, along
844 the specified path. The paint's Align setting determins where along the
845 path to start the text.
846 @param text The text to be drawn
847 @param byteLength The number of bytes to read from the text parameter
848 @param path The path the text should follow for its baseline
849 @param matrix (may be null) Applied to the text before it is
851 @param paint The paint used for the text
853 virtual void drawTextOnPath(const void* text, size_t byteLength,
854 const SkPath& path, const SkMatrix* matrix,
855 const SkPaint& paint);
857 /** Draw the picture into this canvas. This method effective brackets the
858 playback of the picture's draw calls with save/restore, so the state
859 of this canvas will be unchanged after this call.
860 @param picture The recorded drawing commands to playback into this
863 virtual void drawPicture(SkPicture& picture);
866 kTriangles_VertexMode,
867 kTriangleStrip_VertexMode,
868 kTriangleFan_VertexMode
871 /** Draw the array of vertices, interpreted as triangles (based on mode).
872 @param vmode How to interpret the array of vertices
873 @param vertexCount The number of points in the vertices array (and
874 corresponding texs and colors arrays if non-null)
875 @param vertices Array of vertices for the mesh
876 @param texs May be null. If not null, specifies the coordinate
877 in _texture_ space (not uv space) for each vertex.
878 @param colors May be null. If not null, specifies a color for each
879 vertex, to be interpolated across the triangle.
880 @param xmode Used if both texs and colors are present. In this
881 case the colors are combined with the texture using mode,
882 before being drawn using the paint. If mode is null, then
883 kModulate_Mode is used.
884 @param indices If not null, array of indices to reference into the
885 vertex (texs, colors) array.
886 @param indexCount number of entries in the indices array (if not null)
887 @param paint Specifies the shader/texture if present.
889 virtual void drawVertices(VertexMode vmode, int vertexCount,
890 const SkPoint vertices[], const SkPoint texs[],
891 const SkColor colors[], SkXfermode* xmode,
892 const uint16_t indices[], int indexCount,
893 const SkPaint& paint);
895 /** Send a blob of data to the canvas.
896 For canvases that draw, this call is effectively a no-op, as the data
897 is not parsed, but just ignored. However, this call exists for
898 subclasses like SkPicture's recording canvas, that can store the data
899 and then play it back later (via another call to drawData).
901 virtual void drawData(const void* data, size_t length) {
902 // do nothing. Subclasses may do something with the data
905 /** Add comments. beginCommentGroup/endCommentGroup open/close a new group.
906 Each comment added via addComment is notionally attached to its
907 enclosing group. Top-level comments simply belong to no group.
909 virtual void beginCommentGroup(const char* description) {
910 // do nothing. Subclasses may do something
912 virtual void addComment(const char* kywd, const char* value) {
913 // do nothing. Subclasses may do something
915 virtual void endCommentGroup() {
916 // do nothing. Subclasses may do something
920 //////////////////////////////////////////////////////////////////////////
922 /** Get the current bounder object.
923 The bounder's reference count is unchaged.
924 @return the canva's bounder (or NULL).
926 SkBounder* getBounder() const { return fBounder; }
928 /** Set a new bounder (or NULL).
929 Pass NULL to clear any previous bounder.
930 As a convenience, the parameter passed is also returned.
931 If a previous bounder exists, its reference count is decremented.
932 If bounder is not NULL, its reference count is incremented.
933 @param bounder the new bounder (or NULL) to be installed in the canvas
934 @return the set bounder object
936 virtual SkBounder* setBounder(SkBounder* bounder);
938 /** Get the current filter object. The filter's reference count is not
939 affected. The filter is saved/restored, just like the matrix and clip.
940 @return the canvas' filter (or NULL).
942 SkDrawFilter* getDrawFilter() const;
944 /** Set the new filter (or NULL). Pass NULL to clear any existing filter.
945 As a convenience, the parameter is returned. If an existing filter
946 exists, its refcnt is decrement. If the new filter is not null, its
947 refcnt is incremented. The filter is saved/restored, just like the
949 @param filter the new filter (or NULL)
950 @return the new filter
952 virtual SkDrawFilter* setDrawFilter(SkDrawFilter* filter);
954 //////////////////////////////////////////////////////////////////////////
956 /** Return the current matrix on the canvas.
957 This does not account for the translate in any of the devices.
958 @return The current matrix on the canvas.
960 const SkMatrix& getTotalMatrix() const;
968 /** Returns a description of the total clip; may be cheaper than
969 getting the clip and querying it directly.
971 ClipType getClipType() const;
973 /** DEPRECATED -- need to move this guy to private/friend
974 * Return the current device clip (concatenation of all clip calls).
975 * This does not account for the translate in any of the devices.
976 * @return the current device clip (concatenation of all clip calls).
978 const SkRegion& getTotalClip() const;
980 /** Return the clip stack. The clip stack stores all the individual
981 * clips organized by the save/restore frame in which they were
983 * @return the current clip stack ("list" of individual clip elements)
985 const SkClipStack* getClipStack() const {
991 virtual ~ClipVisitor();
992 virtual void clipRect(const SkRect&, SkRegion::Op, bool antialias) = 0;
993 virtual void clipPath(const SkPath&, SkRegion::Op, bool antialias) = 0;
997 * Replays the clip operations, back to front, that have been applied to
998 * the canvas, calling the appropriate method on the visitor for each
999 * clip. All clips have already been transformed into device space.
1001 void replayClips(ClipVisitor*) const;
1003 ///////////////////////////////////////////////////////////////////////////
1005 /** After calling saveLayer(), there can be any number of devices that make
1006 up the top-most drawing area. LayerIter can be used to iterate through
1007 those devices. Note that the iterator is only valid until the next API
1008 call made on the canvas. Ownership of all pointers in the iterator stays
1009 with the canvas, so none of them should be modified or deleted.
1011 class SK_API LayerIter /*: SkNoncopyable*/ {
1013 /** Initialize iterator with canvas, and set values for 1st device */
1014 LayerIter(SkCanvas*, bool skipEmptyClips);
1017 /** Return true if the iterator is done */
1018 bool done() const { return fDone; }
1019 /** Cycle to the next device */
1022 // These reflect the current device in the iterator
1024 SkBaseDevice* device() const;
1025 const SkMatrix& matrix() const;
1026 const SkRegion& clip() const;
1027 const SkPaint& paint() const;
1032 // used to embed the SkDrawIter object directly in our instance, w/o
1033 // having to expose that class def to the public. There is an assert
1034 // in our constructor to ensure that fStorage is large enough
1035 // (though needs to be a compile-time-assert!). We use intptr_t to work
1036 // safely with 32 and 64 bit machines (to ensure the storage is enough)
1037 intptr_t fStorage[32];
1038 class SkDrawIter* fImpl; // this points at fStorage
1039 SkPaint fDefaultPaint;
1044 // default impl defers to getDevice()->newSurface(info)
1045 virtual SkSurface* onNewSurface(const SkImageInfo&);
1047 // default impl defers to its device
1048 virtual const void* onPeekPixels(SkImageInfo*, size_t* rowBytes);
1050 // Returns the canvas to be used by DrawIter. Default implementation
1051 // returns this. Subclasses that encapsulate an indirect canvas may
1052 // need to overload this method. The impl must keep track of this, as it
1053 // is not released or deleted by the caller.
1054 virtual SkCanvas* canvasForDrawIter();
1056 // Clip rectangle bounds. Called internally by saveLayer.
1057 // returns false if the entire rectangle is entirely clipped out
1058 // If non-NULL, The imageFilter parameter will be used to expand the clip
1059 // and offscreen bounds for any margin required by the filter DAG.
1060 bool clipRectBounds(const SkRect* bounds, SaveFlags flags,
1061 SkIRect* intersection,
1062 const SkImageFilter* imageFilter = NULL);
1064 // Called by child classes that override clipPath and clipRRect to only
1065 // track fast conservative clip bounds, rather than exact clips.
1066 bool updateClipConservativelyUsingBounds(const SkRect&, SkRegion::Op,
1067 bool inverseFilled);
1069 // notify our surface (if we have one) that we are about to draw, so it
1070 // can perform copy-on-write or invalidate any cached images
1071 void predrawNotify();
1074 DEPRECATED -- need to remove when subclass stop relying on it.
1075 Marked as 'protected' to avoid new clients using this before we can
1076 completely remove it.
1078 Specify a device for this canvas to draw into. If it is not null, its
1079 reference count is incremented. If the canvas was already holding a
1080 device, its reference count is decremented. The new device is returned.
1082 virtual SkBaseDevice* setDevice(SkBaseDevice* device);
1087 SkClipStack fClipStack;
1089 // points to top of stack
1091 // the first N recs that can fit here mean we won't call malloc
1092 uint32_t fMCRecStorage[32];
1094 SkBounder* fBounder;
1095 int fSaveLayerCount; // number of successful saveLayer calls
1097 SkMetaData* fMetaData;
1099 SkSurface_Base* fSurfaceBase;
1100 SkSurface_Base* getSurfaceBase() const { return fSurfaceBase; }
1101 void setSurfaceBase(SkSurface_Base* sb) {
1104 friend class SkSurface_Base;
1105 friend class SkSurface_Gpu;
1107 bool fDeviceCMDirty; // cleared by updateDeviceCMCache()
1108 void updateDeviceCMCache();
1110 friend class SkDrawIter; // needs setupDrawForLayerDevice()
1111 friend class AutoDrawLooper;
1113 SkBaseDevice* createLayerDevice(SkBitmap::Config, int width, int height,
1116 SkBaseDevice* init(SkBaseDevice*);
1118 // internal methods are not virtual, so they can safely be called by other
1119 // canvas apis, without confusing subclasses (like SkPictureRecording)
1120 void internalDrawBitmap(const SkBitmap&, const SkMatrix& m, const SkPaint* paint);
1121 void internalDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src,
1122 const SkRect& dst, const SkPaint* paint,
1123 DrawBitmapRectFlags flags);
1124 void internalDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
1125 const SkRect& dst, const SkPaint* paint);
1126 void internalDrawPaint(const SkPaint& paint);
1127 int internalSaveLayer(const SkRect* bounds, const SkPaint* paint,
1128 SaveFlags, bool justForImageFilter);
1129 void internalDrawDevice(SkBaseDevice*, int x, int y, const SkPaint*);
1131 // shared by save() and saveLayer()
1132 int internalSave(SaveFlags flags);
1133 void internalRestore();
1134 static void DrawRect(const SkDraw& draw, const SkPaint& paint,
1135 const SkRect& r, SkScalar textSize);
1136 static void DrawTextDecorations(const SkDraw& draw, const SkPaint& paint,
1137 const char text[], size_t byteLength,
1138 SkScalar x, SkScalar y);
1140 /* These maintain a cache of the clip bounds in local coordinates,
1141 (converted to 2s-compliment if floats are slow).
1143 mutable SkRect fCachedLocalClipBounds;
1144 mutable bool fCachedLocalClipBoundsDirty;
1145 bool fAllowSoftClip;
1146 bool fAllowSimplifyClip;
1148 const SkRect& getLocalClipBounds() const {
1149 if (fCachedLocalClipBoundsDirty) {
1150 if (!this->getClipBounds(&fCachedLocalClipBounds)) {
1151 fCachedLocalClipBounds.setEmpty();
1153 fCachedLocalClipBoundsDirty = false;
1155 return fCachedLocalClipBounds;
1158 class AutoValidateClip : ::SkNoncopyable {
1160 explicit AutoValidateClip(SkCanvas* canvas) : fCanvas(canvas) {
1161 fCanvas->validateClip();
1163 ~AutoValidateClip() { fCanvas->validateClip(); }
1166 const SkCanvas* fCanvas;
1170 void validateClip() const;
1172 void validateClip() const {}
1175 typedef SkRefCnt INHERITED;
1178 /** Stack helper class to automatically call restoreToCount() on the canvas
1179 when this object goes out of scope. Use this to guarantee that the canvas
1180 is restored to a known state.
1182 class SkAutoCanvasRestore : SkNoncopyable {
1184 SkAutoCanvasRestore(SkCanvas* canvas, bool doSave) : fCanvas(canvas), fSaveCount(0) {
1186 fSaveCount = canvas->getSaveCount();
1192 ~SkAutoCanvasRestore() {
1194 fCanvas->restoreToCount(fSaveCount);
1199 * Perform the restore now, instead of waiting for the destructor. Will
1200 * only do this once.
1204 fCanvas->restoreToCount(fSaveCount);
1213 #define SkAutoCanvasRestore(...) SK_REQUIRE_LOCAL_VAR(SkAutoCanvasRestore)
1215 /** Stack helper class to automatically open and close a comment block
1217 class SkAutoCommentBlock : SkNoncopyable {
1219 SkAutoCommentBlock(SkCanvas* canvas, const char* description) {
1221 if (NULL != fCanvas) {
1222 fCanvas->beginCommentGroup(description);
1226 ~SkAutoCommentBlock() {
1227 if (NULL != fCanvas) {
1228 fCanvas->endCommentGroup();
1235 #define SkAutoCommentBlock(...) SK_REQUIRE_LOCAL_VAR(SkAutoCommentBlock)
1238 * If the caller wants read-only access to the pixels in a canvas, it can just
1239 * call canvas->peekPixels(), since that is the fastest way to "peek" at the
1240 * pixels on a raster-backed canvas.
1242 * If the canvas has pixels, but they are not readily available to the CPU
1243 * (e.g. gpu-backed), then peekPixels() will fail, but readPixels() will
1244 * succeed (though be slower, since it will return a copy of the pixels).
1246 * SkAutoROCanvasPixels encapsulates these two techniques, trying first to call
1247 * peekPixels() (for performance), but if that fails, calling readPixels() and
1248 * storing the copy locally.
1250 * The caller must respect the restrictions associated with peekPixels(), since
1251 * that may have been called: The returned information is invalidated if...
1252 * - any API is called on the canvas (or its parent surface if present)
1253 * - the canvas goes out of scope
1255 class SkAutoROCanvasPixels : SkNoncopyable {
1257 SkAutoROCanvasPixels(SkCanvas* canvas);
1259 // returns NULL on failure
1260 const void* addr() const { return fAddr; }
1262 // undefined if addr() == NULL
1263 size_t rowBytes() const { return fRowBytes; }
1265 // undefined if addr() == NULL
1266 const SkImageInfo& info() const { return fInfo; }
1268 // helper that, if returns true, installs the pixels into the bitmap. Note
1269 // that the bitmap may reference the address returned by peekPixels(), so
1270 // the caller must respect the restrictions associated with peekPixels().
1271 bool asROBitmap(SkBitmap*) const;
1274 SkBitmap fBitmap; // used if peekPixels() fails
1275 const void* fAddr; // NULL on failure