SkCanvas.h revision e254310a55d55a710309714c48f7fbbe7a6126f7
1 2/* 3 * Copyright 2006 The Android Open Source Project 4 * 5 * Use of this source code is governed by a BSD-style license that can be 6 * found in the LICENSE file. 7 */ 8 9 10#ifndef SkCanvas_DEFINED 11#define SkCanvas_DEFINED 12 13#include "SkTypes.h" 14#include "SkBitmap.h" 15#include "SkDeque.h" 16#include "SkClipStack.h" 17#include "SkPaint.h" 18#include "SkRefCnt.h" 19#include "SkPath.h" 20#include "SkRegion.h" 21#include "SkXfermode.h" 22 23class SkBounder; 24class SkBaseDevice; 25class SkDraw; 26class SkDrawFilter; 27class SkMetaData; 28class SkPicture; 29class SkRRect; 30class SkSurface_Base; 31class GrContext; 32 33/** \class SkCanvas 34 35 A Canvas encapsulates all of the state about drawing into a device (bitmap). 36 This includes a reference to the device itself, and a stack of matrix/clip 37 values. For any given draw call (e.g. drawRect), the geometry of the object 38 being drawn is transformed by the concatenation of all the matrices in the 39 stack. The transformed geometry is clipped by the intersection of all of 40 the clips in the stack. 41 42 While the Canvas holds the state of the drawing device, the state (style) 43 of the object being drawn is held by the Paint, which is provided as a 44 parameter to each of the draw() methods. The Paint holds attributes such as 45 color, typeface, textSize, strokeWidth, shader (e.g. gradients, patterns), 46 etc. 47*/ 48class SK_API SkCanvas : public SkRefCnt { 49public: 50 SK_DECLARE_INST_COUNT(SkCanvas) 51 52 /** 53 * Creates an empty canvas with no backing device/pixels, and zero 54 * dimensions. 55 */ 56 SkCanvas(); 57 58 /** 59 * Creates a canvas of the specified dimensions, but explicitly not backed 60 * by any device/pixels. Typically this use used by subclasses who handle 61 * the draw calls in some other way. 62 */ 63 SkCanvas(int width, int height); 64 65 /** Construct a canvas with the specified device to draw into. 66 67 @param device Specifies a device for the canvas to draw into. 68 */ 69 explicit SkCanvas(SkBaseDevice* device); 70 71 /** Construct a canvas with the specified bitmap to draw into. 72 @param bitmap Specifies a bitmap for the canvas to draw into. Its 73 structure are copied to the canvas. 74 */ 75 explicit SkCanvas(const SkBitmap& bitmap); 76 virtual ~SkCanvas(); 77 78 SkMetaData& getMetaData(); 79 80 /////////////////////////////////////////////////////////////////////////// 81 82 /** 83 * Trigger the immediate execution of all pending draw operations. 84 */ 85 void flush(); 86 87 /** 88 * Return the width/height of the underlying device. The current drawable 89 * area may be small (due to clipping or saveLayer). For a canvas with 90 * no device, 0,0 will be returned. 91 */ 92 SkISize getDeviceSize() const; 93 94 /** Return the canvas' device object, which may be null. The device holds 95 the bitmap of the pixels that the canvas draws into. The reference count 96 of the returned device is not changed by this call. 97 */ 98 SkBaseDevice* getDevice() const; 99 100 /** 101 * saveLayer() can create another device (which is later drawn onto 102 * the previous device). getTopDevice() returns the top-most device current 103 * installed. Note that this can change on other calls like save/restore, 104 * so do not access this device after subsequent canvas calls. 105 * The reference count of the device is not changed. 106 * 107 * @param updateMatrixClip If this is true, then before the device is 108 * returned, we ensure that its has been notified about the current 109 * matrix and clip. Note: this happens automatically when the device 110 * is drawn to, but is optional here, as there is a small perf hit 111 * sometimes. 112 */ 113 SkBaseDevice* getTopDevice(bool updateMatrixClip = false) const; 114 115 /** 116 * Shortcut for getDevice()->createCompatibleDevice(...). 117 * If getDevice() == NULL, this method does nothing, and returns NULL. 118 */ 119 SkBaseDevice* createCompatibleDevice(SkBitmap::Config config, 120 int width, int height, 121 bool isOpaque); 122 123 /** 124 * Return the GPU context of the device that is associated with the canvas. 125 * For a canvas with non-GPU device, NULL is returned. 126 */ 127 GrContext* getGrContext(); 128 129 /////////////////////////////////////////////////////////////////////////// 130 131 /** 132 * This enum can be used with read/writePixels to perform a pixel ops to or 133 * from an 8888 config other than Skia's native config (SkPMColor). There 134 * are three byte orders supported: native, BGRA, and RGBA. Each has a 135 * premultiplied and unpremultiplied variant. 136 * 137 * Components of a 8888 pixel can be packed/unpacked from a 32bit word using 138 * either byte offsets or shift values. Byte offsets are endian-invariant 139 * while shifts are not. BGRA and RGBA configs are defined by byte 140 * orderings. The native config is defined by shift values (SK_A32_SHIFT, 141 * ..., SK_B32_SHIFT). 142 */ 143 enum Config8888 { 144 /** 145 * Skia's native order specified by: 146 * SK_A32_SHIFT, SK_R32_SHIFT, SK_G32_SHIFT, and SK_B32_SHIFT 147 * 148 * kNative_Premul_Config8888 is equivalent to SkPMColor 149 * kNative_Unpremul_Config8888 has the same component order as SkPMColor 150 * but is not premultiplied. 151 */ 152 kNative_Premul_Config8888, 153 kNative_Unpremul_Config8888, 154 /** 155 * low byte to high byte: B, G, R, A. 156 */ 157 kBGRA_Premul_Config8888, 158 kBGRA_Unpremul_Config8888, 159 /** 160 * low byte to high byte: R, G, B, A. 161 */ 162 kRGBA_Premul_Config8888, 163 kRGBA_Unpremul_Config8888 164 }; 165 166 /** 167 * On success (returns true), copy the canvas pixels into the bitmap. 168 * On failure, the bitmap parameter is left unchanged and false is 169 * returned. 170 * 171 * The canvas' pixels are converted to the bitmap's config. The only 172 * supported config is kARGB_8888_Config, though this is likely to be 173 * relaxed in the future. The meaning of config kARGB_8888_Config is 174 * modified by the enum param config8888. The default value interprets 175 * kARGB_8888_Config as SkPMColor 176 * 177 * If the bitmap has pixels already allocated, the canvas pixels will be 178 * written there. If not, bitmap->allocPixels() will be called 179 * automatically. If the bitmap is backed by a texture readPixels will 180 * fail. 181 * 182 * The actual pixels written is the intersection of the canvas' bounds, and 183 * the rectangle formed by the bitmap's width,height and the specified x,y. 184 * If bitmap pixels extend outside of that intersection, they will not be 185 * modified. 186 * 187 * Other failure conditions: 188 * * If the canvas is backed by a non-raster device (e.g. PDF) then 189 * readPixels will fail. 190 * * If bitmap is texture-backed then readPixels will fail. (This may be 191 * relaxed in the future.) 192 * 193 * Example that reads the entire canvas into a bitmap using the native 194 * SkPMColor: 195 * SkISize size = canvas->getDeviceSize(); 196 * bitmap->setConfig(SkBitmap::kARGB_8888_Config, size.fWidth, 197 * size.fHeight); 198 * if (canvas->readPixels(bitmap, 0, 0)) { 199 * // use the pixels 200 * } 201 */ 202 bool readPixels(SkBitmap* bitmap, 203 int x, int y, 204 Config8888 config8888 = kNative_Premul_Config8888); 205 206 /** 207 * DEPRECATED: This will be removed as soon as webkit is no longer relying 208 * on it. The bitmap is resized to the intersection of srcRect and the 209 * canvas bounds. New pixels are always allocated on success. Bitmap is 210 * unmodified on failure. 211 */ 212 bool readPixels(const SkIRect& srcRect, SkBitmap* bitmap); 213 214 /** 215 * Similar to draw sprite, this method will copy the pixels in bitmap onto 216 * the canvas, with the top/left corner specified by (x, y). The canvas' 217 * pixel values are completely replaced: there is no blending. 218 * 219 * Currently if bitmap is backed by a texture this is a no-op. This may be 220 * relaxed in the future. 221 * 222 * If the bitmap has config kARGB_8888_Config then the config8888 param 223 * will determines how the pixel valuess are intepreted. If the bitmap is 224 * not kARGB_8888_Config then this parameter is ignored. 225 * 226 * Note: If you are recording drawing commands on this canvas to 227 * SkPicture, writePixels() is ignored! 228 */ 229 void writePixels(const SkBitmap& bitmap, 230 int x, int y, 231 Config8888 config8888 = kNative_Premul_Config8888); 232 233 /////////////////////////////////////////////////////////////////////////// 234 235 enum SaveFlags { 236 /** save the matrix state, restoring it on restore() */ 237 kMatrix_SaveFlag = 0x01, 238 /** save the clip state, restoring it on restore() */ 239 kClip_SaveFlag = 0x02, 240 /** the layer needs to support per-pixel alpha */ 241 kHasAlphaLayer_SaveFlag = 0x04, 242 /** the layer needs to support 8-bits per color component */ 243 kFullColorLayer_SaveFlag = 0x08, 244 /** the layer should clip against the bounds argument */ 245 kClipToLayer_SaveFlag = 0x10, 246 247 // helper masks for common choices 248 kMatrixClip_SaveFlag = 0x03, 249 kARGB_NoClipLayer_SaveFlag = 0x0F, 250 kARGB_ClipLayer_SaveFlag = 0x1F 251 }; 252 253 /** This call saves the current matrix, clip, and drawFilter, and pushes a 254 copy onto a private stack. Subsequent calls to translate, scale, 255 rotate, skew, concat or clipRect, clipPath, and setDrawFilter all 256 operate on this copy. 257 When the balancing call to restore() is made, the previous matrix, clip, 258 and drawFilter are restored. 259 @param flags The flags govern what portion of the Matrix/Clip/drawFilter 260 state the save (and matching restore) effect. For example, 261 if only kMatrix is specified, then only the matrix state 262 will be pushed and popped. Likewise for the clip if kClip 263 is specified. However, the drawFilter is always affected 264 by calls to save/restore. 265 @return The value to pass to restoreToCount() to balance this save() 266 */ 267 virtual int save(SaveFlags flags = kMatrixClip_SaveFlag); 268 269 /** This behaves the same as save(), but in addition it allocates an 270 offscreen bitmap. All drawing calls are directed there, and only when 271 the balancing call to restore() is made is that offscreen transfered to 272 the canvas (or the previous layer). 273 @param bounds (may be null) This rect, if non-null, is used as a hint to 274 limit the size of the offscreen, and thus drawing may be 275 clipped to it, though that clipping is not guaranteed to 276 happen. If exact clipping is desired, use clipRect(). 277 @param paint (may be null) This is copied, and is applied to the 278 offscreen when restore() is called 279 @param flags LayerFlags 280 @return The value to pass to restoreToCount() to balance this save() 281 */ 282 virtual int saveLayer(const SkRect* bounds, const SkPaint* paint, 283 SaveFlags flags = kARGB_ClipLayer_SaveFlag); 284 285 /** This behaves the same as save(), but in addition it allocates an 286 offscreen bitmap. All drawing calls are directed there, and only when 287 the balancing call to restore() is made is that offscreen transfered to 288 the canvas (or the previous layer). 289 @param bounds (may be null) This rect, if non-null, is used as a hint to 290 limit the size of the offscreen, and thus drawing may be 291 clipped to it, though that clipping is not guaranteed to 292 happen. If exact clipping is desired, use clipRect(). 293 @param alpha This is applied to the offscreen when restore() is called. 294 @param flags LayerFlags 295 @return The value to pass to restoreToCount() to balance this save() 296 */ 297 int saveLayerAlpha(const SkRect* bounds, U8CPU alpha, 298 SaveFlags flags = kARGB_ClipLayer_SaveFlag); 299 300 /** This call balances a previous call to save(), and is used to remove all 301 modifications to the matrix/clip/drawFilter state since the last save 302 call. 303 It is an error to call restore() more times than save() was called. 304 */ 305 virtual void restore(); 306 307 /** Returns the number of matrix/clip states on the SkCanvas' private stack. 308 This will equal # save() calls - # restore() calls. 309 */ 310 int getSaveCount() const; 311 312 /** Efficient way to pop any calls to save() that happened after the save 313 count reached saveCount. It is an error for saveCount to be less than 314 getSaveCount() 315 @param saveCount The number of save() levels to restore from 316 */ 317 void restoreToCount(int saveCount); 318 319 /** Returns true if drawing is currently going to a layer (from saveLayer) 320 * rather than to the root device. 321 */ 322 virtual bool isDrawingToLayer() const; 323 324 /** Preconcat the current matrix with the specified translation 325 @param dx The distance to translate in X 326 @param dy The distance to translate in Y 327 returns true if the operation succeeded (e.g. did not overflow) 328 */ 329 virtual bool translate(SkScalar dx, SkScalar dy); 330 331 /** Preconcat the current matrix with the specified scale. 332 @param sx The amount to scale in X 333 @param sy The amount to scale in Y 334 returns true if the operation succeeded (e.g. did not overflow) 335 */ 336 virtual bool scale(SkScalar sx, SkScalar sy); 337 338 /** Preconcat the current matrix with the specified rotation. 339 @param degrees The amount to rotate, in degrees 340 returns true if the operation succeeded (e.g. did not overflow) 341 */ 342 virtual bool rotate(SkScalar degrees); 343 344 /** Preconcat the current matrix with the specified skew. 345 @param sx The amount to skew in X 346 @param sy The amount to skew in Y 347 returns true if the operation succeeded (e.g. did not overflow) 348 */ 349 virtual bool skew(SkScalar sx, SkScalar sy); 350 351 /** Preconcat the current matrix with the specified matrix. 352 @param matrix The matrix to preconcatenate with the current matrix 353 @return true if the operation succeeded (e.g. did not overflow) 354 */ 355 virtual bool concat(const SkMatrix& matrix); 356 357 /** Replace the current matrix with a copy of the specified matrix. 358 @param matrix The matrix that will be copied into the current matrix. 359 */ 360 virtual void setMatrix(const SkMatrix& matrix); 361 362 /** Helper for setMatrix(identity). Sets the current matrix to identity. 363 */ 364 void resetMatrix(); 365 366 /** 367 * Modify the current clip with the specified rectangle. 368 * @param rect The rect to combine with the current clip 369 * @param op The region op to apply to the current clip 370 * @param doAntiAlias true if the clip should be antialiased 371 * @return true if the canvas' clip is non-empty 372 */ 373 virtual bool clipRect(const SkRect& rect, 374 SkRegion::Op op = SkRegion::kIntersect_Op, 375 bool doAntiAlias = false); 376 377 /** 378 * Modify the current clip with the specified SkRRect. 379 * @param rrect The rrect to combine with the current clip 380 * @param op The region op to apply to the current clip 381 * @param doAntiAlias true if the clip should be antialiased 382 * @return true if the canvas' clip is non-empty 383 */ 384 virtual bool clipRRect(const SkRRect& rrect, 385 SkRegion::Op op = SkRegion::kIntersect_Op, 386 bool doAntiAlias = false); 387 388 /** 389 * Modify the current clip with the specified path. 390 * @param path The path 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' new clip is non-empty 394 */ 395 virtual bool clipPath(const SkPath& path, 396 SkRegion::Op op = SkRegion::kIntersect_Op, 397 bool doAntiAlias = false); 398 399 /** EXPERIMENTAL -- only used for testing 400 Set to false to force clips to be hard, even if doAntiAlias=true is 401 passed to clipRect or clipPath. 402 */ 403 void setAllowSoftClip(bool allow) { 404 fAllowSoftClip = allow; 405 } 406 407 /** EXPERIMENTAL -- only used for testing 408 Set to simplify clip stack using path ops. 409 */ 410 void setAllowSimplifyClip(bool allow) { 411 fAllowSimplifyClip = allow; 412 } 413 414 /** Modify the current clip with the specified region. Note that unlike 415 clipRect() and clipPath() which transform their arguments by the current 416 matrix, clipRegion() assumes its argument is already in device 417 coordinates, and so no transformation is performed. 418 @param deviceRgn The region to apply to the current clip 419 @param op The region op to apply to the current clip 420 @return true if the canvas' new clip is non-empty 421 */ 422 virtual bool clipRegion(const SkRegion& deviceRgn, 423 SkRegion::Op op = SkRegion::kIntersect_Op); 424 425 /** Helper for clipRegion(rgn, kReplace_Op). Sets the current clip to the 426 specified region. This does not intersect or in any other way account 427 for the existing clip region. 428 @param deviceRgn The region to copy into the current clip. 429 @return true if the new clip region is non-empty 430 */ 431 bool setClipRegion(const SkRegion& deviceRgn) { 432 return this->clipRegion(deviceRgn, SkRegion::kReplace_Op); 433 } 434 435 /** Return true if the specified rectangle, after being transformed by the 436 current matrix, would lie completely outside of the current clip. Call 437 this to check if an area you intend to draw into is clipped out (and 438 therefore you can skip making the draw calls). 439 @param rect the rect to compare with the current clip 440 @return true if the rect (transformed by the canvas' matrix) does not 441 intersect with the canvas' clip 442 */ 443 bool quickReject(const SkRect& rect) const; 444 445 /** Return true if the specified path, after being transformed by the 446 current matrix, would lie completely outside of the current clip. Call 447 this to check if an area you intend to draw into is clipped out (and 448 therefore you can skip making the draw calls). Note, for speed it may 449 return false even if the path itself might not intersect the clip 450 (i.e. the bounds of the path intersects, but the path does not). 451 @param path The path to compare with the current clip 452 @return true if the path (transformed by the canvas' matrix) does not 453 intersect with the canvas' clip 454 */ 455 bool quickReject(const SkPath& path) const; 456 457 /** Return true if the horizontal band specified by top and bottom is 458 completely clipped out. This is a conservative calculation, meaning 459 that it is possible that if the method returns false, the band may still 460 in fact be clipped out, but the converse is not true. If this method 461 returns true, then the band is guaranteed to be clipped out. 462 @param top The top of the horizontal band to compare with the clip 463 @param bottom The bottom of the horizontal and to compare with the clip 464 @return true if the horizontal band is completely clipped out (i.e. does 465 not intersect the current clip) 466 */ 467 bool quickRejectY(SkScalar top, SkScalar bottom) const { 468 SkASSERT(top <= bottom); 469 const SkRect& clipR = this->getLocalClipBounds(); 470 // In the case where the clip is empty and we are provided with a 471 // negative top and positive bottom parameter then this test will return 472 // false even though it will be clipped. We have chosen to exclude that 473 // check as it is rare and would result double the comparisons. 474 return top >= clipR.fBottom || bottom <= clipR.fTop; 475 } 476 477 /** Return the bounds of the current clip (in local coordinates) in the 478 bounds parameter, and return true if it is non-empty. This can be useful 479 in a way similar to quickReject, in that it tells you that drawing 480 outside of these bounds will be clipped out. 481 */ 482 bool getClipBounds(SkRect* bounds) const; 483 484 /** Return the bounds of the current clip, in device coordinates; returns 485 true if non-empty. Maybe faster than getting the clip explicitly and 486 then taking its bounds. 487 */ 488 bool getClipDeviceBounds(SkIRect* bounds) const; 489 490 491 /** Fill the entire canvas' bitmap (restricted to the current clip) with the 492 specified ARGB color, using the specified mode. 493 @param a the alpha component (0..255) of the color to fill the canvas 494 @param r the red component (0..255) of the color to fill the canvas 495 @param g the green component (0..255) of the color to fill the canvas 496 @param b the blue component (0..255) of the color to fill the canvas 497 @param mode the mode to apply the color in (defaults to SrcOver) 498 */ 499 void drawARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b, 500 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode); 501 502 /** Fill the entire canvas' bitmap (restricted to the current clip) with the 503 specified color and mode. 504 @param color the color to draw with 505 @param mode the mode to apply the color in (defaults to SrcOver) 506 */ 507 void drawColor(SkColor color, 508 SkXfermode::Mode mode = SkXfermode::kSrcOver_Mode); 509 510 /** 511 * This erases the entire drawing surface to the specified color, 512 * irrespective of the clip. It does not blend with the previous pixels, 513 * but always overwrites them. 514 * 515 * It is roughly equivalent to the following: 516 * canvas.save(); 517 * canvas.clipRect(hugeRect, kReplace_Op); 518 * paint.setColor(color); 519 * paint.setXfermodeMode(kSrc_Mode); 520 * canvas.drawPaint(paint); 521 * canvas.restore(); 522 * though it is almost always much more efficient. 523 */ 524 virtual void clear(SkColor); 525 526 /** 527 * Fill the entire canvas' bitmap (restricted to the current clip) with the 528 * specified paint. 529 * @param paint The paint used to fill the canvas 530 */ 531 virtual void drawPaint(const SkPaint& paint); 532 533 enum PointMode { 534 /** drawPoints draws each point separately */ 535 kPoints_PointMode, 536 /** drawPoints draws each pair of points as a line segment */ 537 kLines_PointMode, 538 /** drawPoints draws the array of points as a polygon */ 539 kPolygon_PointMode 540 }; 541 542 /** Draw a series of points, interpreted based on the PointMode mode. For 543 all modes, the count parameter is interpreted as the total number of 544 points. For kLine mode, count/2 line segments are drawn. 545 For kPoint mode, each point is drawn centered at its coordinate, and its 546 size is specified by the paint's stroke-width. It draws as a square, 547 unless the paint's cap-type is round, in which the points are drawn as 548 circles. 549 For kLine mode, each pair of points is drawn as a line segment, 550 respecting the paint's settings for cap/join/width. 551 For kPolygon mode, the entire array is drawn as a series of connected 552 line segments. 553 Note that, while similar, kLine and kPolygon modes draw slightly 554 differently than the equivalent path built with a series of moveto, 555 lineto calls, in that the path will draw all of its contours at once, 556 with no interactions if contours intersect each other (think XOR 557 xfermode). drawPoints always draws each element one at a time. 558 @param mode PointMode specifying how to draw the array of points. 559 @param count The number of points in the array 560 @param pts Array of points to draw 561 @param paint The paint used to draw the points 562 */ 563 virtual void drawPoints(PointMode mode, size_t count, const SkPoint pts[], 564 const SkPaint& paint); 565 566 /** Helper method for drawing a single point. See drawPoints() for a more 567 details. 568 */ 569 void drawPoint(SkScalar x, SkScalar y, const SkPaint& paint); 570 571 /** Draws a single pixel in the specified color. 572 @param x The X coordinate of which pixel to draw 573 @param y The Y coordiante of which pixel to draw 574 @param color The color to draw 575 */ 576 void drawPoint(SkScalar x, SkScalar y, SkColor color); 577 578 /** Draw a line segment with the specified start and stop x,y coordinates, 579 using the specified paint. NOTE: since a line is always "framed", the 580 paint's Style is ignored. 581 @param x0 The x-coordinate of the start point of the line 582 @param y0 The y-coordinate of the start point of the line 583 @param x1 The x-coordinate of the end point of the line 584 @param y1 The y-coordinate of the end point of the line 585 @param paint The paint used to draw the line 586 */ 587 void drawLine(SkScalar x0, SkScalar y0, SkScalar x1, SkScalar y1, 588 const SkPaint& paint); 589 590 /** Draw the specified rectangle using the specified paint. The rectangle 591 will be filled or stroked based on the Style in the paint. 592 @param rect The rect to be drawn 593 @param paint The paint used to draw the rect 594 */ 595 virtual void drawRect(const SkRect& rect, const SkPaint& paint); 596 597 /** Draw the specified rectangle using the specified paint. The rectangle 598 will be filled or framed based on the Style in the paint. 599 @param rect The rect to be drawn 600 @param paint The paint used to draw the rect 601 */ 602 void drawIRect(const SkIRect& rect, const SkPaint& paint) 603 { 604 SkRect r; 605 r.set(rect); // promotes the ints to scalars 606 this->drawRect(r, paint); 607 } 608 609 /** Draw the specified rectangle using the specified paint. The rectangle 610 will be filled or framed based on the Style in the paint. 611 @param left The left side of the rectangle to be drawn 612 @param top The top side of the rectangle to be drawn 613 @param right The right side of the rectangle to be drawn 614 @param bottom The bottom side of the rectangle to be drawn 615 @param paint The paint used to draw the rect 616 */ 617 void drawRectCoords(SkScalar left, SkScalar top, SkScalar right, 618 SkScalar bottom, const SkPaint& paint); 619 620 /** Draw the specified oval using the specified paint. The oval will be 621 filled or framed based on the Style in the paint. 622 @param oval The rectangle bounds of the oval to be drawn 623 @param paint The paint used to draw the oval 624 */ 625 virtual void drawOval(const SkRect& oval, const SkPaint&); 626 627 /** 628 * Draw the specified RRect using the specified paint The rrect will be filled or stroked 629 * based on the Style in the paint. 630 * 631 * @param rrect The round-rect to draw 632 * @param paint The paint used to draw the round-rect 633 */ 634 virtual void drawRRect(const SkRRect& rrect, const SkPaint& paint); 635 636 /** Draw the specified circle using the specified paint. If radius is <= 0, 637 then nothing will be drawn. The circle will be filled 638 or framed based on the Style in the paint. 639 @param cx The x-coordinate of the center of the cirle to be drawn 640 @param cy The y-coordinate of the center of the cirle to be drawn 641 @param radius The radius of the cirle to be drawn 642 @param paint The paint used to draw the circle 643 */ 644 void drawCircle(SkScalar cx, SkScalar cy, SkScalar radius, 645 const SkPaint& paint); 646 647 /** Draw the specified arc, which will be scaled to fit inside the 648 specified oval. If the sweep angle is >= 360, then the oval is drawn 649 completely. Note that this differs slightly from SkPath::arcTo, which 650 treats the sweep angle mod 360. 651 @param oval The bounds of oval used to define the shape of the arc 652 @param startAngle Starting angle (in degrees) where the arc begins 653 @param sweepAngle Sweep angle (in degrees) measured clockwise 654 @param useCenter true means include the center of the oval. For filling 655 this will draw a wedge. False means just use the arc. 656 @param paint The paint used to draw the arc 657 */ 658 void drawArc(const SkRect& oval, SkScalar startAngle, SkScalar sweepAngle, 659 bool useCenter, const SkPaint& paint); 660 661 /** Draw the specified round-rect using the specified paint. The round-rect 662 will be filled or framed based on the Style in the paint. 663 @param rect The rectangular bounds of the roundRect to be drawn 664 @param rx The x-radius of the oval used to round the corners 665 @param ry The y-radius of the oval used to round the corners 666 @param paint The paint used to draw the roundRect 667 */ 668 void drawRoundRect(const SkRect& rect, SkScalar rx, SkScalar ry, 669 const SkPaint& paint); 670 671 /** Draw the specified path using the specified paint. The path will be 672 filled or framed based on the Style in the paint. 673 @param path The path to be drawn 674 @param paint The paint used to draw the path 675 */ 676 virtual void drawPath(const SkPath& path, const SkPaint& paint); 677 678 /** Draw the specified bitmap, with its top/left corner at (x,y), using the 679 specified paint, transformed by the current matrix. Note: if the paint 680 contains a maskfilter that generates a mask which extends beyond the 681 bitmap's original width/height, then the bitmap will be drawn as if it 682 were in a Shader with CLAMP mode. Thus the color outside of the original 683 width/height will be the edge color replicated. 684 685 If a shader is present on the paint it will be ignored, except in the 686 case where the bitmap is kA8_Config. In that case, the color is 687 generated by the shader. 688 689 @param bitmap The bitmap to be drawn 690 @param left The position of the left side of the bitmap being drawn 691 @param top The position of the top side of the bitmap being drawn 692 @param paint The paint used to draw the bitmap, or NULL 693 */ 694 virtual void drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top, 695 const SkPaint* paint = NULL); 696 697 enum DrawBitmapRectFlags { 698 kNone_DrawBitmapRectFlag = 0x0, 699 /** 700 * When filtering is enabled, allow the color samples outside of 701 * the src rect (but still in the src bitmap) to bleed into the 702 * drawn portion 703 */ 704 kBleed_DrawBitmapRectFlag = 0x1, 705 }; 706 707 /** Draw the specified bitmap, with the specified matrix applied (before the 708 canvas' matrix is applied). 709 @param bitmap The bitmap to be drawn 710 @param src Optional: specify the subset of the bitmap to be drawn 711 @param dst The destination rectangle where the scaled/translated 712 image will be drawn 713 @param paint The paint used to draw the bitmap, or NULL 714 */ 715 virtual void drawBitmapRectToRect(const SkBitmap& bitmap, const SkRect* src, 716 const SkRect& dst, 717 const SkPaint* paint = NULL, 718 DrawBitmapRectFlags flags = kNone_DrawBitmapRectFlag); 719 720 void drawBitmapRect(const SkBitmap& bitmap, const SkRect& dst, 721 const SkPaint* paint = NULL) { 722 this->drawBitmapRectToRect(bitmap, NULL, dst, paint, kNone_DrawBitmapRectFlag); 723 } 724 725 void drawBitmapRect(const SkBitmap& bitmap, const SkIRect* isrc, 726 const SkRect& dst, const SkPaint* paint = NULL, 727 DrawBitmapRectFlags flags = kNone_DrawBitmapRectFlag) { 728 SkRect realSrcStorage; 729 SkRect* realSrcPtr = NULL; 730 if (isrc) { 731 realSrcStorage.set(*isrc); 732 realSrcPtr = &realSrcStorage; 733 } 734 this->drawBitmapRectToRect(bitmap, realSrcPtr, dst, paint, flags); 735 } 736 737 virtual void drawBitmapMatrix(const SkBitmap& bitmap, const SkMatrix& m, 738 const SkPaint* paint = NULL); 739 740 /** 741 * Draw the bitmap stretched differentially to fit into dst. 742 * center is a rect within the bitmap, and logically divides the bitmap 743 * into 9 sections (3x3). For example, if the middle pixel of a [5x5] 744 * bitmap is the "center", then the center-rect should be [2, 2, 3, 3]. 745 * 746 * If the dst is >= the bitmap size, then... 747 * - The 4 corners are not stretched at all. 748 * - The sides are stretched in only one axis. 749 * - The center is stretched in both axes. 750 * Else, for each axis where dst < bitmap, 751 * - The corners shrink proportionally 752 * - The sides (along the shrink axis) and center are not drawn 753 */ 754 virtual void drawBitmapNine(const SkBitmap& bitmap, const SkIRect& center, 755 const SkRect& dst, const SkPaint* paint = NULL); 756 757 /** Draw the specified bitmap, with its top/left corner at (x,y), 758 NOT transformed by the current matrix. Note: if the paint 759 contains a maskfilter that generates a mask which extends beyond the 760 bitmap's original width/height, then the bitmap will be drawn as if it 761 were in a Shader with CLAMP mode. Thus the color outside of the original 762 width/height will be the edge color replicated. 763 @param bitmap The bitmap to be drawn 764 @param left The position of the left side of the bitmap being drawn 765 @param top The position of the top side of the bitmap being drawn 766 @param paint The paint used to draw the bitmap, or NULL 767 */ 768 virtual void drawSprite(const SkBitmap& bitmap, int left, int top, 769 const SkPaint* paint = NULL); 770 771 /** Draw the text, with origin at (x,y), using the specified paint. 772 The origin is interpreted based on the Align setting in the paint. 773 @param text The text to be drawn 774 @param byteLength The number of bytes to read from the text parameter 775 @param x The x-coordinate of the origin of the text being drawn 776 @param y The y-coordinate of the origin of the text being drawn 777 @param paint The paint used for the text (e.g. color, size, style) 778 */ 779 virtual void drawText(const void* text, size_t byteLength, SkScalar x, 780 SkScalar y, const SkPaint& paint); 781 782 /** Draw the text, with each character/glyph origin specified by the pos[] 783 array. The origin is interpreted by the Align setting in the paint. 784 @param text The text to be drawn 785 @param byteLength The number of bytes to read from the text parameter 786 @param pos Array of positions, used to position each character 787 @param paint The paint used for the text (e.g. color, size, style) 788 */ 789 virtual void drawPosText(const void* text, size_t byteLength, 790 const SkPoint pos[], const SkPaint& paint); 791 792 /** Draw the text, with each character/glyph origin specified by the x 793 coordinate taken from the xpos[] array, and the y from the constY param. 794 The origin is interpreted by 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 xpos Array of x-positions, used to position each character 798 @param constY The shared Y coordinate for all of the positions 799 @param paint The paint used for the text (e.g. color, size, style) 800 */ 801 virtual void drawPosTextH(const void* text, size_t byteLength, 802 const SkScalar xpos[], SkScalar constY, 803 const SkPaint& paint); 804 805 /** Draw the text, with origin at (x,y), using the specified paint, along 806 the specified path. The paint's Align setting determins where along the 807 path to start the text. 808 @param text The text to be drawn 809 @param byteLength The number of bytes to read from the text parameter 810 @param path The path the text should follow for its baseline 811 @param hOffset The distance along the path to add to the text's 812 starting position 813 @param vOffset The distance above(-) or below(+) the path to 814 position the text 815 @param paint The paint used for the text 816 */ 817 void drawTextOnPathHV(const void* text, size_t byteLength, 818 const SkPath& path, SkScalar hOffset, 819 SkScalar vOffset, const SkPaint& paint); 820 821 /** Draw the text, with origin at (x,y), using the specified paint, along 822 the specified path. The paint's Align setting determins where along the 823 path to start the text. 824 @param text The text to be drawn 825 @param byteLength The number of bytes to read from the text parameter 826 @param path The path the text should follow for its baseline 827 @param matrix (may be null) Applied to the text before it is 828 mapped onto the path 829 @param paint The paint used for the text 830 */ 831 virtual void drawTextOnPath(const void* text, size_t byteLength, 832 const SkPath& path, const SkMatrix* matrix, 833 const SkPaint& paint); 834 835 /** Draw the picture into this canvas. This method effective brackets the 836 playback of the picture's draw calls with save/restore, so the state 837 of this canvas will be unchanged after this call. 838 @param picture The recorded drawing commands to playback into this 839 canvas. 840 */ 841 virtual void drawPicture(SkPicture& picture); 842 843 enum VertexMode { 844 kTriangles_VertexMode, 845 kTriangleStrip_VertexMode, 846 kTriangleFan_VertexMode 847 }; 848 849 /** Draw the array of vertices, interpreted as triangles (based on mode). 850 @param vmode How to interpret the array of vertices 851 @param vertexCount The number of points in the vertices array (and 852 corresponding texs and colors arrays if non-null) 853 @param vertices Array of vertices for the mesh 854 @param texs May be null. If not null, specifies the coordinate 855 in _texture_ space (not uv space) for each vertex. 856 @param colors May be null. If not null, specifies a color for each 857 vertex, to be interpolated across the triangle. 858 @param xmode Used if both texs and colors are present. In this 859 case the colors are combined with the texture using mode, 860 before being drawn using the paint. If mode is null, then 861 kModulate_Mode is used. 862 @param indices If not null, array of indices to reference into the 863 vertex (texs, colors) array. 864 @param indexCount number of entries in the indices array (if not null) 865 @param paint Specifies the shader/texture if present. 866 */ 867 virtual void drawVertices(VertexMode vmode, int vertexCount, 868 const SkPoint vertices[], const SkPoint texs[], 869 const SkColor colors[], SkXfermode* xmode, 870 const uint16_t indices[], int indexCount, 871 const SkPaint& paint); 872 873 /** Send a blob of data to the canvas. 874 For canvases that draw, this call is effectively a no-op, as the data 875 is not parsed, but just ignored. However, this call exists for 876 subclasses like SkPicture's recording canvas, that can store the data 877 and then play it back later (via another call to drawData). 878 */ 879 virtual void drawData(const void* data, size_t length) { 880 // do nothing. Subclasses may do something with the data 881 } 882 883 /** Add comments. beginCommentGroup/endCommentGroup open/close a new group. 884 Each comment added via addComment is notionally attached to its 885 enclosing group. Top-level comments simply belong to no group. 886 */ 887 virtual void beginCommentGroup(const char* description) { 888 // do nothing. Subclasses may do something 889 } 890 virtual void addComment(const char* kywd, const char* value) { 891 // do nothing. Subclasses may do something 892 } 893 virtual void endCommentGroup() { 894 // do nothing. Subclasses may do something 895 } 896 897 898 ////////////////////////////////////////////////////////////////////////// 899 900 /** Get the current bounder object. 901 The bounder's reference count is unchaged. 902 @return the canva's bounder (or NULL). 903 */ 904 SkBounder* getBounder() const { return fBounder; } 905 906 /** Set a new bounder (or NULL). 907 Pass NULL to clear any previous bounder. 908 As a convenience, the parameter passed is also returned. 909 If a previous bounder exists, its reference count is decremented. 910 If bounder is not NULL, its reference count is incremented. 911 @param bounder the new bounder (or NULL) to be installed in the canvas 912 @return the set bounder object 913 */ 914 virtual SkBounder* setBounder(SkBounder* bounder); 915 916 /** Get the current filter object. The filter's reference count is not 917 affected. The filter is saved/restored, just like the matrix and clip. 918 @return the canvas' filter (or NULL). 919 */ 920 SkDrawFilter* getDrawFilter() const; 921 922 /** Set the new filter (or NULL). Pass NULL to clear any existing filter. 923 As a convenience, the parameter is returned. If an existing filter 924 exists, its refcnt is decrement. If the new filter is not null, its 925 refcnt is incremented. The filter is saved/restored, just like the 926 matrix and clip. 927 @param filter the new filter (or NULL) 928 @return the new filter 929 */ 930 virtual SkDrawFilter* setDrawFilter(SkDrawFilter* filter); 931 932 ////////////////////////////////////////////////////////////////////////// 933 934 /** Return the current matrix on the canvas. 935 This does not account for the translate in any of the devices. 936 @return The current matrix on the canvas. 937 */ 938 const SkMatrix& getTotalMatrix() const; 939 940 enum ClipType { 941 kEmpty_ClipType = 0, 942 kRect_ClipType, 943 kComplex_ClipType 944 }; 945 946 /** Returns a description of the total clip; may be cheaper than 947 getting the clip and querying it directly. 948 */ 949 ClipType getClipType() const; 950 951 /** DEPRECATED -- need to move this guy to private/friend 952 * Return the current device clip (concatenation of all clip calls). 953 * This does not account for the translate in any of the devices. 954 * @return the current device clip (concatenation of all clip calls). 955 */ 956 const SkRegion& getTotalClip() const; 957 958 /** Return the clip stack. The clip stack stores all the individual 959 * clips organized by the save/restore frame in which they were 960 * added. 961 * @return the current clip stack ("list" of individual clip elements) 962 */ 963 const SkClipStack* getClipStack() const { 964 return &fClipStack; 965 } 966 967 class ClipVisitor { 968 public: 969 virtual ~ClipVisitor(); 970 virtual void clipRect(const SkRect&, SkRegion::Op, bool antialias) = 0; 971 virtual void clipPath(const SkPath&, SkRegion::Op, bool antialias) = 0; 972 }; 973 974 /** 975 * Replays the clip operations, back to front, that have been applied to 976 * the canvas, calling the appropriate method on the visitor for each 977 * clip. All clips have already been transformed into device space. 978 */ 979 void replayClips(ClipVisitor*) const; 980 981 /////////////////////////////////////////////////////////////////////////// 982 983 /** After calling saveLayer(), there can be any number of devices that make 984 up the top-most drawing area. LayerIter can be used to iterate through 985 those devices. Note that the iterator is only valid until the next API 986 call made on the canvas. Ownership of all pointers in the iterator stays 987 with the canvas, so none of them should be modified or deleted. 988 */ 989 class SK_API LayerIter /*: SkNoncopyable*/ { 990 public: 991 /** Initialize iterator with canvas, and set values for 1st device */ 992 LayerIter(SkCanvas*, bool skipEmptyClips); 993 ~LayerIter(); 994 995 /** Return true if the iterator is done */ 996 bool done() const { return fDone; } 997 /** Cycle to the next device */ 998 void next(); 999 1000 // These reflect the current device in the iterator 1001 1002 SkBaseDevice* device() const; 1003 const SkMatrix& matrix() const; 1004 const SkRegion& clip() const; 1005 const SkPaint& paint() const; 1006 int x() const; 1007 int y() const; 1008 1009 private: 1010 // used to embed the SkDrawIter object directly in our instance, w/o 1011 // having to expose that class def to the public. There is an assert 1012 // in our constructor to ensure that fStorage is large enough 1013 // (though needs to be a compile-time-assert!). We use intptr_t to work 1014 // safely with 32 and 64 bit machines (to ensure the storage is enough) 1015 intptr_t fStorage[32]; 1016 class SkDrawIter* fImpl; // this points at fStorage 1017 SkPaint fDefaultPaint; 1018 bool fDone; 1019 }; 1020 1021protected: 1022 // Returns the canvas to be used by DrawIter. Default implementation 1023 // returns this. Subclasses that encapsulate an indirect canvas may 1024 // need to overload this method. The impl must keep track of this, as it 1025 // is not released or deleted by the caller. 1026 virtual SkCanvas* canvasForDrawIter(); 1027 1028 // Clip rectangle bounds. Called internally by saveLayer. 1029 // returns false if the entire rectangle is entirely clipped out 1030 bool clipRectBounds(const SkRect* bounds, SaveFlags flags, 1031 SkIRect* intersection); 1032 1033 // Called by child classes that override clipPath and clipRRect to only 1034 // track fast conservative clip bounds, rather than exact clips. 1035 bool updateClipConservativelyUsingBounds(const SkRect&, SkRegion::Op, 1036 bool inverseFilled); 1037 1038 // notify our surface (if we have one) that we are about to draw, so it 1039 // can perform copy-on-write or invalidate any cached images 1040 void predrawNotify(); 1041 1042 /** 1043 DEPRECATED -- need to remove when subclass stop relying on it. 1044 Marked as 'protected' to avoid new clients using this before we can 1045 completely remove it. 1046 1047 Specify a device for this canvas to draw into. If it is not null, its 1048 reference count is incremented. If the canvas was already holding a 1049 device, its reference count is decremented. The new device is returned. 1050 */ 1051 virtual SkBaseDevice* setDevice(SkBaseDevice* device); 1052 1053private: 1054 class MCRec; 1055 1056 SkClipStack fClipStack; 1057 SkDeque fMCStack; 1058 // points to top of stack 1059 MCRec* fMCRec; 1060 // the first N recs that can fit here mean we won't call malloc 1061 uint32_t fMCRecStorage[32]; 1062 1063 SkBounder* fBounder; 1064 int fSaveLayerCount; // number of successful saveLayer calls 1065 1066 SkMetaData* fMetaData; 1067 1068 SkSurface_Base* fSurfaceBase; 1069 SkSurface_Base* getSurfaceBase() const { return fSurfaceBase; } 1070 void setSurfaceBase(SkSurface_Base* sb) { 1071 fSurfaceBase = sb; 1072 } 1073 friend class SkSurface_Base; 1074 friend class SkSurface_Gpu; 1075 1076 bool fDeviceCMDirty; // cleared by updateDeviceCMCache() 1077 void updateDeviceCMCache(); 1078 1079 friend class SkDrawIter; // needs setupDrawForLayerDevice() 1080 friend class AutoDrawLooper; 1081 1082 SkBaseDevice* createLayerDevice(SkBitmap::Config, int width, int height, 1083 bool isOpaque); 1084 1085 SkBaseDevice* init(SkBaseDevice*); 1086 1087 // internal methods are not virtual, so they can safely be called by other 1088 // canvas apis, without confusing subclasses (like SkPictureRecording) 1089 void internalDrawBitmap(const SkBitmap&, const SkMatrix& m, const SkPaint* paint); 1090 void internalDrawBitmapRect(const SkBitmap& bitmap, const SkRect* src, 1091 const SkRect& dst, const SkPaint* paint, 1092 DrawBitmapRectFlags flags); 1093 void internalDrawBitmapNine(const SkBitmap& bitmap, const SkIRect& center, 1094 const SkRect& dst, const SkPaint* paint); 1095 void internalDrawPaint(const SkPaint& paint); 1096 int internalSaveLayer(const SkRect* bounds, const SkPaint* paint, 1097 SaveFlags, bool justForImageFilter); 1098 void internalDrawDevice(SkBaseDevice*, int x, int y, const SkPaint*); 1099 1100 // shared by save() and saveLayer() 1101 int internalSave(SaveFlags flags); 1102 void internalRestore(); 1103 static void DrawRect(const SkDraw& draw, const SkPaint& paint, 1104 const SkRect& r, SkScalar textSize); 1105 static void DrawTextDecorations(const SkDraw& draw, const SkPaint& paint, 1106 const char text[], size_t byteLength, 1107 SkScalar x, SkScalar y); 1108 1109 /* These maintain a cache of the clip bounds in local coordinates, 1110 (converted to 2s-compliment if floats are slow). 1111 */ 1112 mutable SkRect fCachedLocalClipBounds; 1113 mutable bool fCachedLocalClipBoundsDirty; 1114 bool fAllowSoftClip; 1115 bool fAllowSimplifyClip; 1116 1117 const SkRect& getLocalClipBounds() const { 1118 if (fCachedLocalClipBoundsDirty) { 1119 if (!this->getClipBounds(&fCachedLocalClipBounds)) { 1120 fCachedLocalClipBounds.setEmpty(); 1121 } 1122 fCachedLocalClipBoundsDirty = false; 1123 } 1124 return fCachedLocalClipBounds; 1125 } 1126 1127 class AutoValidateClip : ::SkNoncopyable { 1128 public: 1129 explicit AutoValidateClip(SkCanvas* canvas) : fCanvas(canvas) { 1130 fCanvas->validateClip(); 1131 } 1132 ~AutoValidateClip() { fCanvas->validateClip(); } 1133 1134 private: 1135 const SkCanvas* fCanvas; 1136 }; 1137 1138#ifdef SK_DEBUG 1139 void validateClip() const; 1140#else 1141 void validateClip() const {} 1142#endif 1143 1144 typedef SkRefCnt INHERITED; 1145}; 1146 1147/** Stack helper class to automatically call restoreToCount() on the canvas 1148 when this object goes out of scope. Use this to guarantee that the canvas 1149 is restored to a known state. 1150*/ 1151class SkAutoCanvasRestore : SkNoncopyable { 1152public: 1153 SkAutoCanvasRestore(SkCanvas* canvas, bool doSave) : fCanvas(canvas), fSaveCount(0) { 1154 if (fCanvas) { 1155 fSaveCount = canvas->getSaveCount(); 1156 if (doSave) { 1157 canvas->save(); 1158 } 1159 } 1160 } 1161 ~SkAutoCanvasRestore() { 1162 if (fCanvas) { 1163 fCanvas->restoreToCount(fSaveCount); 1164 } 1165 } 1166 1167 /** 1168 * Perform the restore now, instead of waiting for the destructor. Will 1169 * only do this once. 1170 */ 1171 void restore() { 1172 if (fCanvas) { 1173 fCanvas->restoreToCount(fSaveCount); 1174 fCanvas = NULL; 1175 } 1176 } 1177 1178private: 1179 SkCanvas* fCanvas; 1180 int fSaveCount; 1181}; 1182#define SkAutoCanvasRestore(...) SK_REQUIRE_LOCAL_VAR(SkAutoCanvasRestore) 1183 1184/** Stack helper class to automatically open and close a comment block 1185 */ 1186class SkAutoCommentBlock : SkNoncopyable { 1187public: 1188 SkAutoCommentBlock(SkCanvas* canvas, const char* description) { 1189 fCanvas = canvas; 1190 if (NULL != fCanvas) { 1191 fCanvas->beginCommentGroup(description); 1192 } 1193 } 1194 1195 ~SkAutoCommentBlock() { 1196 if (NULL != fCanvas) { 1197 fCanvas->endCommentGroup(); 1198 } 1199 } 1200 1201private: 1202 SkCanvas* fCanvas; 1203}; 1204#define SkAutoCommentBlock(...) SK_REQUIRE_LOCAL_VAR(SkAutoCommentBlock) 1205 1206#endif 1207