1 /* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.graphics; 18 19 import android.text.GraphicsOperations; 20 import android.text.SpannableString; 21 import android.text.SpannedString; 22 import android.text.TextUtils; 23 24 import javax.microedition.khronos.opengles.GL; 25 26 /** 27 * The Canvas class holds the "draw" calls. To draw something, you need 28 * 4 basic components: A Bitmap to hold the pixels, a Canvas to host 29 * the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, 30 * Path, text, Bitmap), and a paint (to describe the colors and styles for the 31 * drawing). 32 * 33 * <div class="special reference"> 34 * <h3>Developer Guides</h3> 35 * <p>For more information about how to use Canvas, read the 36 * <a href="{@docRoot}guide/topics/graphics/2d-graphics.html"> 37 * Canvas and Drawables</a> developer guide.</p></div> 38 */ 39 public class Canvas { 40 41 // assigned in constructors or setBitmap, freed in finalizer 42 /** @hide */ 43 public int mNativeCanvas; 44 45 // may be null 46 private Bitmap mBitmap; 47 48 // optional field set by the caller 49 private DrawFilter mDrawFilter; 50 51 /** 52 * @hide 53 */ 54 protected int mDensity = Bitmap.DENSITY_NONE; 55 56 /** 57 * Used to determine when compatibility scaling is in effect. 58 * 59 * @hide 60 */ 61 protected int mScreenDensity = Bitmap.DENSITY_NONE; 62 63 // Used by native code 64 @SuppressWarnings("UnusedDeclaration") 65 private int mSurfaceFormat; 66 67 /** 68 * Flag for drawTextRun indicating left-to-right run direction. 69 * @hide 70 */ 71 public static final int DIRECTION_LTR = 0; 72 73 /** 74 * Flag for drawTextRun indicating right-to-left run direction. 75 * @hide 76 */ 77 public static final int DIRECTION_RTL = 1; 78 79 // Maximum bitmap size as defined in Skia's native code 80 // (see SkCanvas.cpp, SkDraw.cpp) 81 private static final int MAXMIMUM_BITMAP_SIZE = 32766; 82 83 // This field is used to finalize the native Canvas properly 84 private final CanvasFinalizer mFinalizer; 85 86 private static final class CanvasFinalizer { 87 private int mNativeCanvas; 88 89 public CanvasFinalizer(int nativeCanvas) { 90 mNativeCanvas = nativeCanvas; 91 } 92 93 @Override 94 protected void finalize() throws Throwable { 95 try { 96 dispose(); 97 } finally { 98 super.finalize(); 99 } 100 } 101 102 public void dispose() { 103 if (mNativeCanvas != 0) { 104 finalizer(mNativeCanvas); 105 mNativeCanvas = 0; 106 } 107 } 108 } 109 110 /** 111 * Construct an empty raster canvas. Use setBitmap() to specify a bitmap to 112 * draw into. The initial target density is {@link Bitmap#DENSITY_NONE}; 113 * this will typically be replaced when a target bitmap is set for the 114 * canvas. 115 */ 116 public Canvas() { 117 if (!isHardwareAccelerated()) { 118 // 0 means no native bitmap 119 mNativeCanvas = initRaster(0); 120 mFinalizer = new CanvasFinalizer(mNativeCanvas); 121 } else { 122 mFinalizer = null; 123 } 124 } 125 126 /** 127 * Construct a canvas with the specified bitmap to draw into. The bitmap 128 * must be mutable. 129 * 130 * <p>The initial target density of the canvas is the same as the given 131 * bitmap's density. 132 * 133 * @param bitmap Specifies a mutable bitmap for the canvas to draw into. 134 */ 135 public Canvas(Bitmap bitmap) { 136 if (!bitmap.isMutable()) { 137 throw new IllegalStateException("Immutable bitmap passed to Canvas constructor"); 138 } 139 throwIfCannotDraw(bitmap); 140 mNativeCanvas = initRaster(bitmap.ni()); 141 mFinalizer = new CanvasFinalizer(mNativeCanvas); 142 mBitmap = bitmap; 143 mDensity = bitmap.mDensity; 144 } 145 146 /** @hide */ 147 public Canvas(int nativeCanvas) { 148 if (nativeCanvas == 0) { 149 throw new IllegalStateException(); 150 } 151 mNativeCanvas = nativeCanvas; 152 mFinalizer = new CanvasFinalizer(mNativeCanvas); 153 mDensity = Bitmap.getDefaultDensity(); 154 } 155 156 /** 157 * Replace existing canvas while ensuring that the swap has occurred before 158 * the previous native canvas is unreferenced. 159 */ 160 private void safeCanvasSwap(int nativeCanvas, boolean copyState) { 161 final int oldCanvas = mNativeCanvas; 162 mNativeCanvas = nativeCanvas; 163 mFinalizer.mNativeCanvas = nativeCanvas; 164 if (copyState) { 165 copyNativeCanvasState(oldCanvas, mNativeCanvas); 166 } 167 finalizer(oldCanvas); 168 } 169 170 /** 171 * Gets the native canvas pointer. 172 * 173 * @return The native pointer. 174 * 175 * @hide 176 */ 177 public int getNativeCanvas() { 178 return mNativeCanvas; 179 } 180 181 /** 182 * Returns null. 183 * 184 * @deprecated This method is not supported and should not be invoked. 185 * 186 * @hide 187 */ 188 @Deprecated 189 protected GL getGL() { 190 return null; 191 } 192 193 /** 194 * Indicates whether this Canvas uses hardware acceleration. 195 * 196 * Note that this method does not define what type of hardware acceleration 197 * may or may not be used. 198 * 199 * @return True if drawing operations are hardware accelerated, 200 * false otherwise. 201 */ 202 public boolean isHardwareAccelerated() { 203 return false; 204 } 205 206 /** 207 * Specify a bitmap for the canvas to draw into. All canvas state such as 208 * layers, filters, and the save/restore stack are reset with the exception 209 * of the current matrix and clip stack. Additionally, as a side-effect 210 * the canvas' target density is updated to match that of the bitmap. 211 * 212 * @param bitmap Specifies a mutable bitmap for the canvas to draw into. 213 * @see #setDensity(int) 214 * @see #getDensity() 215 */ 216 public void setBitmap(Bitmap bitmap) { 217 if (isHardwareAccelerated()) { 218 throw new RuntimeException("Can't set a bitmap device on a GL canvas"); 219 } 220 221 if (bitmap == null) { 222 safeCanvasSwap(initRaster(0), false); 223 mDensity = Bitmap.DENSITY_NONE; 224 } else { 225 if (!bitmap.isMutable()) { 226 throw new IllegalStateException(); 227 } 228 throwIfCannotDraw(bitmap); 229 230 safeCanvasSwap(initRaster(bitmap.ni()), true); 231 mDensity = bitmap.mDensity; 232 } 233 234 mBitmap = bitmap; 235 } 236 237 /** 238 * Set the viewport dimensions if this canvas is GL based. If it is not, 239 * this method is ignored and no exception is thrown. 240 * 241 * @param width The width of the viewport 242 * @param height The height of the viewport 243 * 244 * @hide 245 */ 246 public void setViewport(int width, int height) { 247 } 248 249 /** 250 * Return true if the device that the current layer draws into is opaque 251 * (i.e. does not support per-pixel alpha). 252 * 253 * @return true if the device that the current layer draws into is opaque 254 */ 255 public native boolean isOpaque(); 256 257 /** 258 * Returns the width of the current drawing layer 259 * 260 * @return the width of the current drawing layer 261 */ 262 public native int getWidth(); 263 264 /** 265 * Returns the height of the current drawing layer 266 * 267 * @return the height of the current drawing layer 268 */ 269 public native int getHeight(); 270 271 /** 272 * <p>Returns the target density of the canvas. The default density is 273 * derived from the density of its backing bitmap, or 274 * {@link Bitmap#DENSITY_NONE} if there is not one.</p> 275 * 276 * @return Returns the current target density of the canvas, which is used 277 * to determine the scaling factor when drawing a bitmap into it. 278 * 279 * @see #setDensity(int) 280 * @see Bitmap#getDensity() 281 */ 282 public int getDensity() { 283 return mDensity; 284 } 285 286 /** 287 * <p>Specifies the density for this Canvas' backing bitmap. This modifies 288 * the target density of the canvas itself, as well as the density of its 289 * backing bitmap via {@link Bitmap#setDensity(int) Bitmap.setDensity(int)}. 290 * 291 * @param density The new target density of the canvas, which is used 292 * to determine the scaling factor when drawing a bitmap into it. Use 293 * {@link Bitmap#DENSITY_NONE} to disable bitmap scaling. 294 * 295 * @see #getDensity() 296 * @see Bitmap#setDensity(int) 297 */ 298 public void setDensity(int density) { 299 if (mBitmap != null) { 300 mBitmap.setDensity(density); 301 } 302 mDensity = density; 303 } 304 305 /** @hide */ 306 public void setScreenDensity(int density) { 307 mScreenDensity = density; 308 } 309 310 /** 311 * Returns the maximum allowed width for bitmaps drawn with this canvas. 312 * Attempting to draw with a bitmap wider than this value will result 313 * in an error. 314 * 315 * @see #getMaximumBitmapHeight() 316 */ 317 public int getMaximumBitmapWidth() { 318 return MAXMIMUM_BITMAP_SIZE; 319 } 320 321 /** 322 * Returns the maximum allowed height for bitmaps drawn with this canvas. 323 * Attempting to draw with a bitmap taller than this value will result 324 * in an error. 325 * 326 * @see #getMaximumBitmapWidth() 327 */ 328 public int getMaximumBitmapHeight() { 329 return MAXMIMUM_BITMAP_SIZE; 330 } 331 332 // the SAVE_FLAG constants must match their native equivalents 333 334 /** restore the current matrix when restore() is called */ 335 public static final int MATRIX_SAVE_FLAG = 0x01; 336 /** restore the current clip when restore() is called */ 337 public static final int CLIP_SAVE_FLAG = 0x02; 338 /** the layer needs to per-pixel alpha */ 339 public static final int HAS_ALPHA_LAYER_SAVE_FLAG = 0x04; 340 /** the layer needs to 8-bits per color component */ 341 public static final int FULL_COLOR_LAYER_SAVE_FLAG = 0x08; 342 /** clip against the layer's bounds */ 343 public static final int CLIP_TO_LAYER_SAVE_FLAG = 0x10; 344 /** restore everything when restore() is called */ 345 public static final int ALL_SAVE_FLAG = 0x1F; 346 347 /** 348 * Saves the current matrix and clip onto a private stack. Subsequent 349 * calls to translate,scale,rotate,skew,concat or clipRect,clipPath 350 * will all operate as usual, but when the balancing call to restore() 351 * is made, those calls will be forgotten, and the settings that existed 352 * before the save() will be reinstated. 353 * 354 * @return The value to pass to restoreToCount() to balance this save() 355 */ 356 public native int save(); 357 358 /** 359 * Based on saveFlags, can save the current matrix and clip onto a private 360 * stack. Subsequent calls to translate,scale,rotate,skew,concat or 361 * clipRect,clipPath will all operate as usual, but when the balancing 362 * call to restore() is made, those calls will be forgotten, and the 363 * settings that existed before the save() will be reinstated. 364 * 365 * @param saveFlags flag bits that specify which parts of the Canvas state 366 * to save/restore 367 * @return The value to pass to restoreToCount() to balance this save() 368 */ 369 public native int save(int saveFlags); 370 371 /** 372 * This behaves the same as save(), but in addition it allocates an 373 * offscreen bitmap. All drawing calls are directed there, and only when 374 * the balancing call to restore() is made is that offscreen transfered to 375 * the canvas (or the previous layer). Subsequent calls to translate, 376 * scale, rotate, skew, concat or clipRect, clipPath all operate on this 377 * copy. When the balancing call to restore() is made, this copy is 378 * deleted and the previous matrix/clip state is restored. 379 * 380 * @param bounds May be null. The maximum size the offscreen bitmap 381 * needs to be (in local coordinates) 382 * @param paint This is copied, and is applied to the offscreen when 383 * restore() is called. 384 * @param saveFlags see _SAVE_FLAG constants 385 * @return value to pass to restoreToCount() to balance this save() 386 */ 387 public int saveLayer(RectF bounds, Paint paint, int saveFlags) { 388 return native_saveLayer(mNativeCanvas, bounds, 389 paint != null ? paint.mNativePaint : 0, 390 saveFlags); 391 } 392 393 /** 394 * Helper version of saveLayer() that takes 4 values rather than a RectF. 395 */ 396 public int saveLayer(float left, float top, float right, float bottom, Paint paint, 397 int saveFlags) { 398 return native_saveLayer(mNativeCanvas, left, top, right, bottom, 399 paint != null ? paint.mNativePaint : 0, 400 saveFlags); 401 } 402 403 /** 404 * This behaves the same as save(), but in addition it allocates an 405 * offscreen bitmap. All drawing calls are directed there, and only when 406 * the balancing call to restore() is made is that offscreen transfered to 407 * the canvas (or the previous layer). Subsequent calls to translate, 408 * scale, rotate, skew, concat or clipRect, clipPath all operate on this 409 * copy. When the balancing call to restore() is made, this copy is 410 * deleted and the previous matrix/clip state is restored. 411 * 412 * @param bounds The maximum size the offscreen bitmap needs to be 413 * (in local coordinates) 414 * @param alpha The alpha to apply to the offscreen when when it is 415 drawn during restore() 416 * @param saveFlags see _SAVE_FLAG constants 417 * @return value to pass to restoreToCount() to balance this call 418 */ 419 public int saveLayerAlpha(RectF bounds, int alpha, int saveFlags) { 420 alpha = Math.min(255, Math.max(0, alpha)); 421 return native_saveLayerAlpha(mNativeCanvas, bounds, alpha, saveFlags); 422 } 423 424 /** 425 * Helper for saveLayerAlpha() that takes 4 values instead of a RectF. 426 */ 427 public int saveLayerAlpha(float left, float top, float right, float bottom, int alpha, 428 int saveFlags) { 429 return native_saveLayerAlpha(mNativeCanvas, left, top, right, bottom, 430 alpha, saveFlags); 431 } 432 433 /** 434 * This call balances a previous call to save(), and is used to remove all 435 * modifications to the matrix/clip state since the last save call. It is 436 * an error to call restore() more times than save() was called. 437 */ 438 public native void restore(); 439 440 /** 441 * Returns the number of matrix/clip states on the Canvas' private stack. 442 * This will equal # save() calls - # restore() calls. 443 */ 444 public native int getSaveCount(); 445 446 /** 447 * Efficient way to pop any calls to save() that happened after the save 448 * count reached saveCount. It is an error for saveCount to be less than 1. 449 * 450 * Example: 451 * int count = canvas.save(); 452 * ... // more calls potentially to save() 453 * canvas.restoreToCount(count); 454 * // now the canvas is back in the same state it was before the initial 455 * // call to save(). 456 * 457 * @param saveCount The save level to restore to. 458 */ 459 public native void restoreToCount(int saveCount); 460 461 /** 462 * Preconcat the current matrix with the specified translation 463 * 464 * @param dx The distance to translate in X 465 * @param dy The distance to translate in Y 466 */ 467 public native void translate(float dx, float dy); 468 469 /** 470 * Preconcat the current matrix with the specified scale. 471 * 472 * @param sx The amount to scale in X 473 * @param sy The amount to scale in Y 474 */ 475 public native void scale(float sx, float sy); 476 477 /** 478 * Preconcat the current matrix with the specified scale. 479 * 480 * @param sx The amount to scale in X 481 * @param sy The amount to scale in Y 482 * @param px The x-coord for the pivot point (unchanged by the scale) 483 * @param py The y-coord for the pivot point (unchanged by the scale) 484 */ 485 public final void scale(float sx, float sy, float px, float py) { 486 translate(px, py); 487 scale(sx, sy); 488 translate(-px, -py); 489 } 490 491 /** 492 * Preconcat the current matrix with the specified rotation. 493 * 494 * @param degrees The amount to rotate, in degrees 495 */ 496 public native void rotate(float degrees); 497 498 /** 499 * Preconcat the current matrix with the specified rotation. 500 * 501 * @param degrees The amount to rotate, in degrees 502 * @param px The x-coord for the pivot point (unchanged by the rotation) 503 * @param py The y-coord for the pivot point (unchanged by the rotation) 504 */ 505 public final void rotate(float degrees, float px, float py) { 506 translate(px, py); 507 rotate(degrees); 508 translate(-px, -py); 509 } 510 511 /** 512 * Preconcat the current matrix with the specified skew. 513 * 514 * @param sx The amount to skew in X 515 * @param sy The amount to skew in Y 516 */ 517 public native void skew(float sx, float sy); 518 519 /** 520 * Preconcat the current matrix with the specified matrix. If the specified 521 * matrix is null, this method does nothing. 522 * 523 * @param matrix The matrix to preconcatenate with the current matrix 524 */ 525 public void concat(Matrix matrix) { 526 if (matrix != null) native_concat(mNativeCanvas, matrix.native_instance); 527 } 528 529 /** 530 * Completely replace the current matrix with the specified matrix. If the 531 * matrix parameter is null, then the current matrix is reset to identity. 532 * 533 * <strong>Note:</strong> it is recommended to use {@link #concat(Matrix)}, 534 * {@link #scale(float, float)}, {@link #translate(float, float)} and 535 * {@link #rotate(float)} instead of this method. 536 * 537 * @param matrix The matrix to replace the current matrix with. If it is 538 * null, set the current matrix to identity. 539 * 540 * @see #concat(Matrix) 541 */ 542 public void setMatrix(Matrix matrix) { 543 native_setMatrix(mNativeCanvas, 544 matrix == null ? 0 : matrix.native_instance); 545 } 546 547 /** 548 * Return, in ctm, the current transformation matrix. This does not alter 549 * the matrix in the canvas, but just returns a copy of it. 550 */ 551 @Deprecated 552 public void getMatrix(Matrix ctm) { 553 native_getCTM(mNativeCanvas, ctm.native_instance); 554 } 555 556 /** 557 * Return a new matrix with a copy of the canvas' current transformation 558 * matrix. 559 */ 560 @Deprecated 561 public final Matrix getMatrix() { 562 Matrix m = new Matrix(); 563 //noinspection deprecation 564 getMatrix(m); 565 return m; 566 } 567 568 /** 569 * Modify the current clip with the specified rectangle. 570 * 571 * @param rect The rect to intersect with the current clip 572 * @param op How the clip is modified 573 * @return true if the resulting clip is non-empty 574 */ 575 public boolean clipRect(RectF rect, Region.Op op) { 576 return native_clipRect(mNativeCanvas, rect.left, rect.top, rect.right, rect.bottom, 577 op.nativeInt); 578 } 579 580 /** 581 * Modify the current clip with the specified rectangle, which is 582 * expressed in local coordinates. 583 * 584 * @param rect The rectangle to intersect with the current clip. 585 * @param op How the clip is modified 586 * @return true if the resulting clip is non-empty 587 */ 588 public boolean clipRect(Rect rect, Region.Op op) { 589 return native_clipRect(mNativeCanvas, rect.left, rect.top, rect.right, rect.bottom, 590 op.nativeInt); 591 } 592 593 /** 594 * Intersect the current clip with the specified rectangle, which is 595 * expressed in local coordinates. 596 * 597 * @param rect The rectangle to intersect with the current clip. 598 * @return true if the resulting clip is non-empty 599 */ 600 public native boolean clipRect(RectF rect); 601 602 /** 603 * Intersect the current clip with the specified rectangle, which is 604 * expressed in local coordinates. 605 * 606 * @param rect The rectangle to intersect with the current clip. 607 * @return true if the resulting clip is non-empty 608 */ 609 public native boolean clipRect(Rect rect); 610 611 /** 612 * Modify the current clip with the specified rectangle, which is 613 * expressed in local coordinates. 614 * 615 * @param left The left side of the rectangle to intersect with the 616 * current clip 617 * @param top The top of the rectangle to intersect with the current 618 * clip 619 * @param right The right side of the rectangle to intersect with the 620 * current clip 621 * @param bottom The bottom of the rectangle to intersect with the current 622 * clip 623 * @param op How the clip is modified 624 * @return true if the resulting clip is non-empty 625 */ 626 public boolean clipRect(float left, float top, float right, float bottom, Region.Op op) { 627 return native_clipRect(mNativeCanvas, left, top, right, bottom, op.nativeInt); 628 } 629 630 /** 631 * Intersect the current clip with the specified rectangle, which is 632 * expressed in local coordinates. 633 * 634 * @param left The left side of the rectangle to intersect with the 635 * current clip 636 * @param top The top of the rectangle to intersect with the current clip 637 * @param right The right side of the rectangle to intersect with the 638 * current clip 639 * @param bottom The bottom of the rectangle to intersect with the current 640 * clip 641 * @return true if the resulting clip is non-empty 642 */ 643 public native boolean clipRect(float left, float top, float right, float bottom); 644 645 /** 646 * Intersect the current clip with the specified rectangle, which is 647 * expressed in local coordinates. 648 * 649 * @param left The left side of the rectangle to intersect with the 650 * current clip 651 * @param top The top of the rectangle to intersect with the current clip 652 * @param right The right side of the rectangle to intersect with the 653 * current clip 654 * @param bottom The bottom of the rectangle to intersect with the current 655 * clip 656 * @return true if the resulting clip is non-empty 657 */ 658 public native boolean clipRect(int left, int top, int right, int bottom); 659 660 /** 661 * Modify the current clip with the specified path. 662 * 663 * @param path The path to operate on the current clip 664 * @param op How the clip is modified 665 * @return true if the resulting is non-empty 666 */ 667 public boolean clipPath(Path path, Region.Op op) { 668 return native_clipPath(mNativeCanvas, path.ni(), op.nativeInt); 669 } 670 671 /** 672 * Intersect the current clip with the specified path. 673 * 674 * @param path The path to intersect with the current clip 675 * @return true if the resulting is non-empty 676 */ 677 public boolean clipPath(Path path) { 678 return clipPath(path, Region.Op.INTERSECT); 679 } 680 681 /** 682 * Modify the current clip with the specified region. Note that unlike 683 * clipRect() and clipPath() which transform their arguments by the 684 * current matrix, clipRegion() assumes its argument is already in the 685 * coordinate system of the current layer's bitmap, and so not 686 * transformation is performed. 687 * 688 * @param region The region to operate on the current clip, based on op 689 * @param op How the clip is modified 690 * @return true if the resulting is non-empty 691 */ 692 public boolean clipRegion(Region region, Region.Op op) { 693 return native_clipRegion(mNativeCanvas, region.ni(), op.nativeInt); 694 } 695 696 /** 697 * Intersect the current clip with the specified region. Note that unlike 698 * clipRect() and clipPath() which transform their arguments by the 699 * current matrix, clipRegion() assumes its argument is already in the 700 * coordinate system of the current layer's bitmap, and so not 701 * transformation is performed. 702 * 703 * @param region The region to operate on the current clip, based on op 704 * @return true if the resulting is non-empty 705 */ 706 public boolean clipRegion(Region region) { 707 return clipRegion(region, Region.Op.INTERSECT); 708 } 709 710 public DrawFilter getDrawFilter() { 711 return mDrawFilter; 712 } 713 714 public void setDrawFilter(DrawFilter filter) { 715 int nativeFilter = 0; 716 if (filter != null) { 717 nativeFilter = filter.mNativeInt; 718 } 719 mDrawFilter = filter; 720 nativeSetDrawFilter(mNativeCanvas, nativeFilter); 721 } 722 723 public enum EdgeType { 724 725 /** 726 * Black-and-White: Treat edges by just rounding to nearest pixel boundary 727 */ 728 BW(0), //!< treat edges by just rounding to nearest pixel boundary 729 730 /** 731 * Antialiased: Treat edges by rounding-out, since they may be antialiased 732 */ 733 AA(1); 734 735 EdgeType(int nativeInt) { 736 this.nativeInt = nativeInt; 737 } 738 739 /** 740 * @hide 741 */ 742 public final int nativeInt; 743 } 744 745 /** 746 * Return true if the specified rectangle, after being transformed by the 747 * current matrix, would lie completely outside of the current clip. Call 748 * this to check if an area you intend to draw into is clipped out (and 749 * therefore you can skip making the draw calls). 750 * 751 * @param rect the rect to compare with the current clip 752 * @param type {@link Canvas.EdgeType#AA} if the path should be considered antialiased, 753 * since that means it may affect a larger area (more pixels) than 754 * non-antialiased ({@link Canvas.EdgeType#BW}). 755 * @return true if the rect (transformed by the canvas' matrix) 756 * does not intersect with the canvas' clip 757 */ 758 public boolean quickReject(RectF rect, EdgeType type) { 759 return native_quickReject(mNativeCanvas, rect); 760 } 761 762 /** 763 * Return true if the specified path, after being transformed by the 764 * current matrix, would lie completely outside of the current clip. Call 765 * this to check if an area you intend to draw into is clipped out (and 766 * therefore you can skip making the draw calls). Note: for speed it may 767 * return false even if the path itself might not intersect the clip 768 * (i.e. the bounds of the path intersects, but the path does not). 769 * 770 * @param path The path to compare with the current clip 771 * @param type {@link Canvas.EdgeType#AA} if the path should be considered antialiased, 772 * since that means it may affect a larger area (more pixels) than 773 * non-antialiased ({@link Canvas.EdgeType#BW}). 774 * @return true if the path (transformed by the canvas' matrix) 775 * does not intersect with the canvas' clip 776 */ 777 public boolean quickReject(Path path, EdgeType type) { 778 return native_quickReject(mNativeCanvas, path.ni()); 779 } 780 781 /** 782 * Return true if the specified rectangle, after being transformed by the 783 * current matrix, would lie completely outside of the current clip. Call 784 * this to check if an area you intend to draw into is clipped out (and 785 * therefore you can skip making the draw calls). 786 * 787 * @param left The left side of the rectangle to compare with the 788 * current clip 789 * @param top The top of the rectangle to compare with the current 790 * clip 791 * @param right The right side of the rectangle to compare with the 792 * current clip 793 * @param bottom The bottom of the rectangle to compare with the 794 * current clip 795 * @param type {@link Canvas.EdgeType#AA} if the path should be considered antialiased, 796 * since that means it may affect a larger area (more pixels) than 797 * non-antialiased ({@link Canvas.EdgeType#BW}). 798 * @return true if the rect (transformed by the canvas' matrix) 799 * does not intersect with the canvas' clip 800 */ 801 public boolean quickReject(float left, float top, float right, float bottom, 802 EdgeType type) { 803 return native_quickReject(mNativeCanvas, left, top, right, bottom); 804 } 805 806 /** 807 * Return the bounds of the current clip (in local coordinates) in the 808 * bounds parameter, and return true if it is non-empty. This can be useful 809 * in a way similar to quickReject, in that it tells you that drawing 810 * outside of these bounds will be clipped out. 811 * 812 * @param bounds Return the clip bounds here. If it is null, ignore it but 813 * still return true if the current clip is non-empty. 814 * @return true if the current clip is non-empty. 815 */ 816 public boolean getClipBounds(Rect bounds) { 817 return native_getClipBounds(mNativeCanvas, bounds); 818 } 819 820 /** 821 * Retrieve the bounds of the current clip (in local coordinates). 822 * 823 * @return the clip bounds, or [0, 0, 0, 0] if the clip is empty. 824 */ 825 public final Rect getClipBounds() { 826 Rect r = new Rect(); 827 getClipBounds(r); 828 return r; 829 } 830 831 /** 832 * Fill the entire canvas' bitmap (restricted to the current clip) with the 833 * specified RGB color, using srcover porterduff mode. 834 * 835 * @param r red component (0..255) of the color to draw onto the canvas 836 * @param g green component (0..255) of the color to draw onto the canvas 837 * @param b blue component (0..255) of the color to draw onto the canvas 838 */ 839 public void drawRGB(int r, int g, int b) { 840 native_drawRGB(mNativeCanvas, r, g, b); 841 } 842 843 /** 844 * Fill the entire canvas' bitmap (restricted to the current clip) with the 845 * specified ARGB color, using srcover porterduff mode. 846 * 847 * @param a alpha component (0..255) of the color to draw onto the canvas 848 * @param r red component (0..255) of the color to draw onto the canvas 849 * @param g green component (0..255) of the color to draw onto the canvas 850 * @param b blue component (0..255) of the color to draw onto the canvas 851 */ 852 public void drawARGB(int a, int r, int g, int b) { 853 native_drawARGB(mNativeCanvas, a, r, g, b); 854 } 855 856 /** 857 * Fill the entire canvas' bitmap (restricted to the current clip) with the 858 * specified color, using srcover porterduff mode. 859 * 860 * @param color the color to draw onto the canvas 861 */ 862 public void drawColor(int color) { 863 native_drawColor(mNativeCanvas, color); 864 } 865 866 /** 867 * Fill the entire canvas' bitmap (restricted to the current clip) with the 868 * specified color and porter-duff xfermode. 869 * 870 * @param color the color to draw with 871 * @param mode the porter-duff mode to apply to the color 872 */ 873 public void drawColor(int color, PorterDuff.Mode mode) { 874 native_drawColor(mNativeCanvas, color, mode.nativeInt); 875 } 876 877 /** 878 * Fill the entire canvas' bitmap (restricted to the current clip) with 879 * the specified paint. This is equivalent (but faster) to drawing an 880 * infinitely large rectangle with the specified paint. 881 * 882 * @param paint The paint used to draw onto the canvas 883 */ 884 public void drawPaint(Paint paint) { 885 native_drawPaint(mNativeCanvas, paint.mNativePaint); 886 } 887 888 /** 889 * Draw a series of points. Each point is centered at the coordinate 890 * specified by pts[], and its diameter is specified by the paint's stroke 891 * width (as transformed by the canvas' CTM), with special treatment for 892 * a stroke width of 0, which always draws exactly 1 pixel (or at most 4 893 * if antialiasing is enabled). The shape of the point is controlled by 894 * the paint's Cap type. The shape is a square, unless the cap type is 895 * Round, in which case the shape is a circle. 896 * 897 * @param pts Array of points to draw [x0 y0 x1 y1 x2 y2 ...] 898 * @param offset Number of values to skip before starting to draw. 899 * @param count The number of values to process, after skipping offset 900 * of them. Since one point uses two values, the number of 901 * "points" that are drawn is really (count >> 1). 902 * @param paint The paint used to draw the points 903 */ 904 public native void drawPoints(float[] pts, int offset, int count, Paint paint); 905 906 /** 907 * Helper for drawPoints() that assumes you want to draw the entire array 908 */ 909 public void drawPoints(float[] pts, Paint paint) { 910 drawPoints(pts, 0, pts.length, paint); 911 } 912 913 /** 914 * Helper for drawPoints() for drawing a single point. 915 */ 916 public native void drawPoint(float x, float y, Paint paint); 917 918 /** 919 * Draw a line segment with the specified start and stop x,y coordinates, 920 * using the specified paint. 921 * 922 * <p>Note that since a line is always "framed", the Style is ignored in the paint.</p> 923 * 924 * <p>Degenerate lines (length is 0) will not be drawn.</p> 925 * 926 * @param startX The x-coordinate of the start point of the line 927 * @param startY The y-coordinate of the start point of the line 928 * @param paint The paint used to draw the line 929 */ 930 public void drawLine(float startX, float startY, float stopX, float stopY, Paint paint) { 931 native_drawLine(mNativeCanvas, startX, startY, stopX, stopY, paint.mNativePaint); 932 } 933 934 /** 935 * Draw a series of lines. Each line is taken from 4 consecutive values 936 * in the pts array. Thus to draw 1 line, the array must contain at least 4 937 * values. This is logically the same as drawing the array as follows: 938 * drawLine(pts[0], pts[1], pts[2], pts[3]) followed by 939 * drawLine(pts[4], pts[5], pts[6], pts[7]) and so on. 940 * 941 * @param pts Array of points to draw [x0 y0 x1 y1 x2 y2 ...] 942 * @param offset Number of values in the array to skip before drawing. 943 * @param count The number of values in the array to process, after 944 * skipping "offset" of them. Since each line uses 4 values, 945 * the number of "lines" that are drawn is really 946 * (count >> 2). 947 * @param paint The paint used to draw the points 948 */ 949 public native void drawLines(float[] pts, int offset, int count, Paint paint); 950 951 public void drawLines(float[] pts, Paint paint) { 952 drawLines(pts, 0, pts.length, paint); 953 } 954 955 /** 956 * Draw the specified Rect using the specified paint. The rectangle will 957 * be filled or framed based on the Style in the paint. 958 * 959 * @param rect The rect to be drawn 960 * @param paint The paint used to draw the rect 961 */ 962 public void drawRect(RectF rect, Paint paint) { 963 native_drawRect(mNativeCanvas, rect, paint.mNativePaint); 964 } 965 966 /** 967 * Draw the specified Rect using the specified Paint. The rectangle 968 * will be filled or framed based on the Style in the paint. 969 * 970 * @param r The rectangle to be drawn. 971 * @param paint The paint used to draw the rectangle 972 */ 973 public void drawRect(Rect r, Paint paint) { 974 drawRect(r.left, r.top, r.right, r.bottom, paint); 975 } 976 977 978 /** 979 * Draw the specified Rect using the specified paint. The rectangle will 980 * be filled or framed based on the Style in the paint. 981 * 982 * @param left The left side of the rectangle to be drawn 983 * @param top The top side of the rectangle to be drawn 984 * @param right The right side of the rectangle to be drawn 985 * @param bottom The bottom side of the rectangle to be drawn 986 * @param paint The paint used to draw the rect 987 */ 988 public void drawRect(float left, float top, float right, float bottom, Paint paint) { 989 native_drawRect(mNativeCanvas, left, top, right, bottom, paint.mNativePaint); 990 } 991 992 /** 993 * Draw the specified oval using the specified paint. The oval will be 994 * filled or framed based on the Style in the paint. 995 * 996 * @param oval The rectangle bounds of the oval to be drawn 997 */ 998 public void drawOval(RectF oval, Paint paint) { 999 if (oval == null) { 1000 throw new NullPointerException(); 1001 } 1002 native_drawOval(mNativeCanvas, oval, paint.mNativePaint); 1003 } 1004 1005 /** 1006 * Draw the specified circle using the specified paint. If radius is <= 0, 1007 * then nothing will be drawn. The circle will be filled or framed based 1008 * on the Style in the paint. 1009 * 1010 * @param cx The x-coordinate of the center of the cirle to be drawn 1011 * @param cy The y-coordinate of the center of the cirle to be drawn 1012 * @param radius The radius of the cirle to be drawn 1013 * @param paint The paint used to draw the circle 1014 */ 1015 public void drawCircle(float cx, float cy, float radius, Paint paint) { 1016 native_drawCircle(mNativeCanvas, cx, cy, radius, paint.mNativePaint); 1017 } 1018 1019 /** 1020 * <p>Draw the specified arc, which will be scaled to fit inside the 1021 * specified oval.</p> 1022 * 1023 * <p>If the start angle is negative or >= 360, the start angle is treated 1024 * as start angle modulo 360.</p> 1025 * 1026 * <p>If the sweep angle is >= 360, then the oval is drawn 1027 * completely. Note that this differs slightly from SkPath::arcTo, which 1028 * treats the sweep angle modulo 360. If the sweep angle is negative, 1029 * the sweep angle is treated as sweep angle modulo 360</p> 1030 * 1031 * <p>The arc is drawn clockwise. An angle of 0 degrees correspond to the 1032 * geometric angle of 0 degrees (3 o'clock on a watch.)</p> 1033 * 1034 * @param oval The bounds of oval used to define the shape and size 1035 * of the arc 1036 * @param startAngle Starting angle (in degrees) where the arc begins 1037 * @param sweepAngle Sweep angle (in degrees) measured clockwise 1038 * @param useCenter If true, include the center of the oval in the arc, and 1039 close it if it is being stroked. This will draw a wedge 1040 * @param paint The paint used to draw the arc 1041 */ 1042 public void drawArc(RectF oval, float startAngle, float sweepAngle, boolean useCenter, 1043 Paint paint) { 1044 if (oval == null) { 1045 throw new NullPointerException(); 1046 } 1047 native_drawArc(mNativeCanvas, oval, startAngle, sweepAngle, 1048 useCenter, paint.mNativePaint); 1049 } 1050 1051 /** 1052 * Draw the specified round-rect using the specified paint. The roundrect 1053 * will be filled or framed based on the Style in the paint. 1054 * 1055 * @param rect The rectangular bounds of the roundRect to be drawn 1056 * @param rx The x-radius of the oval used to round the corners 1057 * @param ry The y-radius of the oval used to round the corners 1058 * @param paint The paint used to draw the roundRect 1059 */ 1060 public void drawRoundRect(RectF rect, float rx, float ry, Paint paint) { 1061 if (rect == null) { 1062 throw new NullPointerException(); 1063 } 1064 native_drawRoundRect(mNativeCanvas, rect, rx, ry, 1065 paint.mNativePaint); 1066 } 1067 1068 /** 1069 * Draw the specified path using the specified paint. The path will be 1070 * filled or framed based on the Style in the paint. 1071 * 1072 * @param path The path to be drawn 1073 * @param paint The paint used to draw the path 1074 */ 1075 public void drawPath(Path path, Paint paint) { 1076 native_drawPath(mNativeCanvas, path.ni(), paint.mNativePaint); 1077 } 1078 1079 /** 1080 * @hide 1081 */ 1082 protected static void throwIfCannotDraw(Bitmap bitmap) { 1083 if (bitmap.isRecycled()) { 1084 throw new RuntimeException("Canvas: trying to use a recycled bitmap " + bitmap); 1085 } 1086 if (!bitmap.isPremultiplied() && bitmap.getConfig() == Bitmap.Config.ARGB_8888 && 1087 bitmap.hasAlpha()) { 1088 throw new RuntimeException("Canvas: trying to use a non-premultiplied bitmap " 1089 + bitmap); 1090 } 1091 } 1092 1093 /** 1094 * Draws the specified bitmap as an N-patch (most often, a 9-patches.) 1095 * 1096 * @param patch The ninepatch object to render 1097 * @param dst The destination rectangle. 1098 * @param paint The paint to draw the bitmap with. may be null 1099 * 1100 * @hide 1101 */ 1102 public void drawPatch(NinePatch patch, Rect dst, Paint paint) { 1103 patch.drawSoftware(this, dst, paint); 1104 } 1105 1106 /** 1107 * Draws the specified bitmap as an N-patch (most often, a 9-patches.) 1108 * 1109 * @param patch The ninepatch object to render 1110 * @param dst The destination rectangle. 1111 * @param paint The paint to draw the bitmap with. may be null 1112 * 1113 * @hide 1114 */ 1115 public void drawPatch(NinePatch patch, RectF dst, Paint paint) { 1116 patch.drawSoftware(this, dst, paint); 1117 } 1118 1119 /** 1120 * Draw the specified bitmap, with its top/left corner at (x,y), using 1121 * the specified paint, transformed by the current matrix. 1122 * 1123 * <p>Note: if the paint contains a maskfilter that generates a mask which 1124 * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter), 1125 * then the bitmap will be drawn as if it were in a Shader with CLAMP mode. 1126 * Thus the color outside of the original width/height will be the edge 1127 * color replicated. 1128 * 1129 * <p>If the bitmap and canvas have different densities, this function 1130 * will take care of automatically scaling the bitmap to draw at the 1131 * same density as the canvas. 1132 * 1133 * @param bitmap The bitmap to be drawn 1134 * @param left The position of the left side of the bitmap being drawn 1135 * @param top The position of the top side of the bitmap being drawn 1136 * @param paint The paint used to draw the bitmap (may be null) 1137 */ 1138 public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) { 1139 throwIfCannotDraw(bitmap); 1140 native_drawBitmap(mNativeCanvas, bitmap.ni(), left, top, 1141 paint != null ? paint.mNativePaint : 0, mDensity, mScreenDensity, bitmap.mDensity); 1142 } 1143 1144 /** 1145 * Draw the specified bitmap, scaling/translating automatically to fill 1146 * the destination rectangle. If the source rectangle is not null, it 1147 * specifies the subset of the bitmap to draw. 1148 * 1149 * <p>Note: if the paint contains a maskfilter that generates a mask which 1150 * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter), 1151 * then the bitmap will be drawn as if it were in a Shader with CLAMP mode. 1152 * Thus the color outside of the original width/height will be the edge 1153 * color replicated. 1154 * 1155 * <p>This function <em>ignores the density associated with the bitmap</em>. 1156 * This is because the source and destination rectangle coordinate 1157 * spaces are in their respective densities, so must already have the 1158 * appropriate scaling factor applied. 1159 * 1160 * @param bitmap The bitmap to be drawn 1161 * @param src May be null. The subset of the bitmap to be drawn 1162 * @param dst The rectangle that the bitmap will be scaled/translated 1163 * to fit into 1164 * @param paint May be null. The paint used to draw the bitmap 1165 */ 1166 public void drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint) { 1167 if (dst == null) { 1168 throw new NullPointerException(); 1169 } 1170 throwIfCannotDraw(bitmap); 1171 native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst, 1172 paint != null ? paint.mNativePaint : 0, mScreenDensity, bitmap.mDensity); 1173 } 1174 1175 /** 1176 * Draw the specified bitmap, scaling/translating automatically to fill 1177 * the destination rectangle. If the source rectangle is not null, it 1178 * specifies the subset of the bitmap to draw. 1179 * 1180 * <p>Note: if the paint contains a maskfilter that generates a mask which 1181 * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter), 1182 * then the bitmap will be drawn as if it were in a Shader with CLAMP mode. 1183 * Thus the color outside of the original width/height will be the edge 1184 * color replicated. 1185 * 1186 * <p>This function <em>ignores the density associated with the bitmap</em>. 1187 * This is because the source and destination rectangle coordinate 1188 * spaces are in their respective densities, so must already have the 1189 * appropriate scaling factor applied. 1190 * 1191 * @param bitmap The bitmap to be drawn 1192 * @param src May be null. The subset of the bitmap to be drawn 1193 * @param dst The rectangle that the bitmap will be scaled/translated 1194 * to fit into 1195 * @param paint May be null. The paint used to draw the bitmap 1196 */ 1197 public void drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) { 1198 if (dst == null) { 1199 throw new NullPointerException(); 1200 } 1201 throwIfCannotDraw(bitmap); 1202 native_drawBitmap(mNativeCanvas, bitmap.ni(), src, dst, 1203 paint != null ? paint.mNativePaint : 0, mScreenDensity, bitmap.mDensity); 1204 } 1205 1206 /** 1207 * Treat the specified array of colors as a bitmap, and draw it. This gives 1208 * the same result as first creating a bitmap from the array, and then 1209 * drawing it, but this method avoids explicitly creating a bitmap object 1210 * which can be more efficient if the colors are changing often. 1211 * 1212 * @param colors Array of colors representing the pixels of the bitmap 1213 * @param offset Offset into the array of colors for the first pixel 1214 * @param stride The number of colors in the array between rows (must be 1215 * >= width or <= -width). 1216 * @param x The X coordinate for where to draw the bitmap 1217 * @param y The Y coordinate for where to draw the bitmap 1218 * @param width The width of the bitmap 1219 * @param height The height of the bitmap 1220 * @param hasAlpha True if the alpha channel of the colors contains valid 1221 * values. If false, the alpha byte is ignored (assumed to 1222 * be 0xFF for every pixel). 1223 * @param paint May be null. The paint used to draw the bitmap 1224 */ 1225 public void drawBitmap(int[] colors, int offset, int stride, float x, float y, 1226 int width, int height, boolean hasAlpha, Paint paint) { 1227 // check for valid input 1228 if (width < 0) { 1229 throw new IllegalArgumentException("width must be >= 0"); 1230 } 1231 if (height < 0) { 1232 throw new IllegalArgumentException("height must be >= 0"); 1233 } 1234 if (Math.abs(stride) < width) { 1235 throw new IllegalArgumentException("abs(stride) must be >= width"); 1236 } 1237 int lastScanline = offset + (height - 1) * stride; 1238 int length = colors.length; 1239 if (offset < 0 || (offset + width > length) || lastScanline < 0 1240 || (lastScanline + width > length)) { 1241 throw new ArrayIndexOutOfBoundsException(); 1242 } 1243 // quick escape if there's nothing to draw 1244 if (width == 0 || height == 0) { 1245 return; 1246 } 1247 // punch down to native for the actual draw 1248 native_drawBitmap(mNativeCanvas, colors, offset, stride, x, y, width, height, hasAlpha, 1249 paint != null ? paint.mNativePaint : 0); 1250 } 1251 1252 /** Legacy version of drawBitmap(int[] colors, ...) that took ints for x,y 1253 */ 1254 public void drawBitmap(int[] colors, int offset, int stride, int x, int y, 1255 int width, int height, boolean hasAlpha, Paint paint) { 1256 // call through to the common float version 1257 drawBitmap(colors, offset, stride, (float)x, (float)y, width, height, 1258 hasAlpha, paint); 1259 } 1260 1261 /** 1262 * Draw the bitmap using the specified matrix. 1263 * 1264 * @param bitmap The bitmap to draw 1265 * @param matrix The matrix used to transform the bitmap when it is drawn 1266 * @param paint May be null. The paint used to draw the bitmap 1267 */ 1268 public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) { 1269 nativeDrawBitmapMatrix(mNativeCanvas, bitmap.ni(), matrix.ni(), 1270 paint != null ? paint.mNativePaint : 0); 1271 } 1272 1273 /** 1274 * @hide 1275 */ 1276 protected static void checkRange(int length, int offset, int count) { 1277 if ((offset | count) < 0 || offset + count > length) { 1278 throw new ArrayIndexOutOfBoundsException(); 1279 } 1280 } 1281 1282 /** 1283 * Draw the bitmap through the mesh, where mesh vertices are evenly 1284 * distributed across the bitmap. There are meshWidth+1 vertices across, and 1285 * meshHeight+1 vertices down. The verts array is accessed in row-major 1286 * order, so that the first meshWidth+1 vertices are distributed across the 1287 * top of the bitmap from left to right. A more general version of this 1288 * method is drawVertices(). 1289 * 1290 * @param bitmap The bitmap to draw using the mesh 1291 * @param meshWidth The number of columns in the mesh. Nothing is drawn if 1292 * this is 0 1293 * @param meshHeight The number of rows in the mesh. Nothing is drawn if 1294 * this is 0 1295 * @param verts Array of x,y pairs, specifying where the mesh should be 1296 * drawn. There must be at least 1297 * (meshWidth+1) * (meshHeight+1) * 2 + vertOffset values 1298 * in the array 1299 * @param vertOffset Number of verts elements to skip before drawing 1300 * @param colors May be null. Specifies a color at each vertex, which is 1301 * interpolated across the cell, and whose values are 1302 * multiplied by the corresponding bitmap colors. If not null, 1303 * there must be at least (meshWidth+1) * (meshHeight+1) + 1304 * colorOffset values in the array. 1305 * @param colorOffset Number of color elements to skip before drawing 1306 * @param paint May be null. The paint used to draw the bitmap 1307 */ 1308 public void drawBitmapMesh(Bitmap bitmap, int meshWidth, int meshHeight, 1309 float[] verts, int vertOffset, int[] colors, int colorOffset, Paint paint) { 1310 if ((meshWidth | meshHeight | vertOffset | colorOffset) < 0) { 1311 throw new ArrayIndexOutOfBoundsException(); 1312 } 1313 if (meshWidth == 0 || meshHeight == 0) { 1314 return; 1315 } 1316 int count = (meshWidth + 1) * (meshHeight + 1); 1317 // we mul by 2 since we need two floats per vertex 1318 checkRange(verts.length, vertOffset, count * 2); 1319 if (colors != null) { 1320 // no mul by 2, since we need only 1 color per vertex 1321 checkRange(colors.length, colorOffset, count); 1322 } 1323 nativeDrawBitmapMesh(mNativeCanvas, bitmap.ni(), meshWidth, meshHeight, 1324 verts, vertOffset, colors, colorOffset, 1325 paint != null ? paint.mNativePaint : 0); 1326 } 1327 1328 public enum VertexMode { 1329 TRIANGLES(0), 1330 TRIANGLE_STRIP(1), 1331 TRIANGLE_FAN(2); 1332 1333 VertexMode(int nativeInt) { 1334 this.nativeInt = nativeInt; 1335 } 1336 1337 /** 1338 * @hide 1339 */ 1340 public final int nativeInt; 1341 } 1342 1343 /** 1344 * Draw the array of vertices, interpreted as triangles (based on mode). The 1345 * verts array is required, and specifies the x,y pairs for each vertex. If 1346 * texs is non-null, then it is used to specify the coordinate in shader 1347 * coordinates to use at each vertex (the paint must have a shader in this 1348 * case). If there is no texs array, but there is a color array, then each 1349 * color is interpolated across its corresponding triangle in a gradient. If 1350 * both texs and colors arrays are present, then they behave as before, but 1351 * the resulting color at each pixels is the result of multiplying the 1352 * colors from the shader and the color-gradient together. The indices array 1353 * is optional, but if it is present, then it is used to specify the index 1354 * of each triangle, rather than just walking through the arrays in order. 1355 * 1356 * @param mode How to interpret the array of vertices 1357 * @param vertexCount The number of values in the vertices array (and 1358 * corresponding texs and colors arrays if non-null). Each logical 1359 * vertex is two values (x, y), vertexCount must be a multiple of 2. 1360 * @param verts Array of vertices for the mesh 1361 * @param vertOffset Number of values in the verts to skip before drawing. 1362 * @param texs May be null. If not null, specifies the coordinates to sample 1363 * into the current shader (e.g. bitmap tile or gradient) 1364 * @param texOffset Number of values in texs to skip before drawing. 1365 * @param colors May be null. If not null, specifies a color for each 1366 * vertex, to be interpolated across the triangle. 1367 * @param colorOffset Number of values in colors to skip before drawing. 1368 * @param indices If not null, array of indices to reference into the 1369 * vertex (texs, colors) array. 1370 * @param indexCount number of entries in the indices array (if not null). 1371 * @param paint Specifies the shader to use if the texs array is non-null. 1372 */ 1373 public void drawVertices(VertexMode mode, int vertexCount, float[] verts, int vertOffset, 1374 float[] texs, int texOffset, int[] colors, int colorOffset, 1375 short[] indices, int indexOffset, int indexCount, Paint paint) { 1376 checkRange(verts.length, vertOffset, vertexCount); 1377 if (texs != null) { 1378 checkRange(texs.length, texOffset, vertexCount); 1379 } 1380 if (colors != null) { 1381 checkRange(colors.length, colorOffset, vertexCount / 2); 1382 } 1383 if (indices != null) { 1384 checkRange(indices.length, indexOffset, indexCount); 1385 } 1386 nativeDrawVertices(mNativeCanvas, mode.nativeInt, vertexCount, verts, 1387 vertOffset, texs, texOffset, colors, colorOffset, 1388 indices, indexOffset, indexCount, paint.mNativePaint); 1389 } 1390 1391 /** 1392 * Draw the text, with origin at (x,y), using the specified paint. The 1393 * origin is interpreted based on the Align setting in the paint. 1394 * 1395 * @param text The text to be drawn 1396 * @param x The x-coordinate of the origin of the text being drawn 1397 * @param y The y-coordinate of the origin of the text being drawn 1398 * @param paint The paint used for the text (e.g. color, size, style) 1399 */ 1400 public void drawText(char[] text, int index, int count, float x, float y, Paint paint) { 1401 if ((index | count | (index + count) | 1402 (text.length - index - count)) < 0) { 1403 throw new IndexOutOfBoundsException(); 1404 } 1405 native_drawText(mNativeCanvas, text, index, count, x, y, paint.mBidiFlags, 1406 paint.mNativePaint); 1407 } 1408 1409 /** 1410 * Draw the text, with origin at (x,y), using the specified paint. The 1411 * origin is interpreted based on the Align setting in the paint. 1412 * 1413 * @param text The text to be drawn 1414 * @param x The x-coordinate of the origin of the text being drawn 1415 * @param y The y-coordinate of the origin of the text being drawn 1416 * @param paint The paint used for the text (e.g. color, size, style) 1417 */ 1418 public void drawText(String text, float x, float y, Paint paint) { 1419 native_drawText(mNativeCanvas, text, 0, text.length(), x, y, paint.mBidiFlags, 1420 paint.mNativePaint); 1421 } 1422 1423 /** 1424 * Draw the text, with origin at (x,y), using the specified paint. 1425 * The origin is interpreted based on the Align setting in the paint. 1426 * 1427 * @param text The text to be drawn 1428 * @param start The index of the first character in text to draw 1429 * @param end (end - 1) is the index of the last character in text to draw 1430 * @param x The x-coordinate of the origin of the text being drawn 1431 * @param y The y-coordinate of the origin of the text being drawn 1432 * @param paint The paint used for the text (e.g. color, size, style) 1433 */ 1434 public void drawText(String text, int start, int end, float x, float y, Paint paint) { 1435 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1436 throw new IndexOutOfBoundsException(); 1437 } 1438 native_drawText(mNativeCanvas, text, start, end, x, y, paint.mBidiFlags, 1439 paint.mNativePaint); 1440 } 1441 1442 /** 1443 * Draw the specified range of text, specified by start/end, with its 1444 * origin at (x,y), in the specified Paint. The origin is interpreted 1445 * based on the Align setting in the Paint. 1446 * 1447 * @param text The text to be drawn 1448 * @param start The index of the first character in text to draw 1449 * @param end (end - 1) is the index of the last character in text 1450 * to draw 1451 * @param x The x-coordinate of origin for where to draw the text 1452 * @param y The y-coordinate of origin for where to draw the text 1453 * @param paint The paint used for the text (e.g. color, size, style) 1454 */ 1455 public void drawText(CharSequence text, int start, int end, float x, float y, Paint paint) { 1456 if (text instanceof String || text instanceof SpannedString || 1457 text instanceof SpannableString) { 1458 native_drawText(mNativeCanvas, text.toString(), start, end, x, y, 1459 paint.mBidiFlags, paint.mNativePaint); 1460 } else if (text instanceof GraphicsOperations) { 1461 ((GraphicsOperations) text).drawText(this, start, end, x, y, 1462 paint); 1463 } else { 1464 char[] buf = TemporaryBuffer.obtain(end - start); 1465 TextUtils.getChars(text, start, end, buf, 0); 1466 native_drawText(mNativeCanvas, buf, 0, end - start, x, y, 1467 paint.mBidiFlags, paint.mNativePaint); 1468 TemporaryBuffer.recycle(buf); 1469 } 1470 } 1471 1472 /** 1473 * Render a run of all LTR or all RTL text, with shaping. This does not run 1474 * bidi on the provided text, but renders it as a uniform right-to-left or 1475 * left-to-right run, as indicated by dir. Alignment of the text is as 1476 * determined by the Paint's TextAlign value. 1477 * 1478 * @param text the text to render 1479 * @param index the start of the text to render 1480 * @param count the count of chars to render 1481 * @param contextIndex the start of the context for shaping. Must be 1482 * no greater than index. 1483 * @param contextCount the number of characters in the context for shaping. 1484 * ContexIndex + contextCount must be no less than index 1485 * + count. 1486 * @param x the x position at which to draw the text 1487 * @param y the y position at which to draw the text 1488 * @param dir the run direction, either {@link #DIRECTION_LTR} or 1489 * {@link #DIRECTION_RTL}. 1490 * @param paint the paint 1491 * @hide 1492 */ 1493 public void drawTextRun(char[] text, int index, int count, int contextIndex, int contextCount, 1494 float x, float y, int dir, Paint paint) { 1495 1496 if (text == null) { 1497 throw new NullPointerException("text is null"); 1498 } 1499 if (paint == null) { 1500 throw new NullPointerException("paint is null"); 1501 } 1502 if ((index | count | text.length - index - count) < 0) { 1503 throw new IndexOutOfBoundsException(); 1504 } 1505 if (dir != DIRECTION_LTR && dir != DIRECTION_RTL) { 1506 throw new IllegalArgumentException("unknown dir: " + dir); 1507 } 1508 1509 native_drawTextRun(mNativeCanvas, text, index, count, 1510 contextIndex, contextCount, x, y, dir, paint.mNativePaint); 1511 } 1512 1513 /** 1514 * Render a run of all LTR or all RTL text, with shaping. This does not run 1515 * bidi on the provided text, but renders it as a uniform right-to-left or 1516 * left-to-right run, as indicated by dir. Alignment of the text is as 1517 * determined by the Paint's TextAlign value. 1518 * 1519 * @param text the text to render 1520 * @param start the start of the text to render. Data before this position 1521 * can be used for shaping context. 1522 * @param end the end of the text to render. Data at or after this 1523 * position can be used for shaping context. 1524 * @param x the x position at which to draw the text 1525 * @param y the y position at which to draw the text 1526 * @param dir the run direction, either 0 for LTR or 1 for RTL. 1527 * @param paint the paint 1528 * @hide 1529 */ 1530 public void drawTextRun(CharSequence text, int start, int end, int contextStart, int contextEnd, 1531 float x, float y, int dir, Paint paint) { 1532 1533 if (text == null) { 1534 throw new NullPointerException("text is null"); 1535 } 1536 if (paint == null) { 1537 throw new NullPointerException("paint is null"); 1538 } 1539 if ((start | end | end - start | text.length() - end) < 0) { 1540 throw new IndexOutOfBoundsException(); 1541 } 1542 1543 int flags = dir == 0 ? 0 : 1; 1544 1545 if (text instanceof String || text instanceof SpannedString || 1546 text instanceof SpannableString) { 1547 native_drawTextRun(mNativeCanvas, text.toString(), start, end, 1548 contextStart, contextEnd, x, y, flags, paint.mNativePaint); 1549 } else if (text instanceof GraphicsOperations) { 1550 ((GraphicsOperations) text).drawTextRun(this, start, end, 1551 contextStart, contextEnd, x, y, flags, paint); 1552 } else { 1553 int contextLen = contextEnd - contextStart; 1554 int len = end - start; 1555 char[] buf = TemporaryBuffer.obtain(contextLen); 1556 TextUtils.getChars(text, contextStart, contextEnd, buf, 0); 1557 native_drawTextRun(mNativeCanvas, buf, start - contextStart, len, 1558 0, contextLen, x, y, flags, paint.mNativePaint); 1559 TemporaryBuffer.recycle(buf); 1560 } 1561 } 1562 1563 /** 1564 * Draw the text in the array, with each character's origin specified by 1565 * the pos array. 1566 * 1567 * This method does not support glyph composition and decomposition and 1568 * should therefore not be used to render complex scripts. 1569 * 1570 * @param text The text to be drawn 1571 * @param index The index of the first character to draw 1572 * @param count The number of characters to draw, starting from index. 1573 * @param pos Array of [x,y] positions, used to position each 1574 * character 1575 * @param paint The paint used for the text (e.g. color, size, style) 1576 */ 1577 @Deprecated 1578 public void drawPosText(char[] text, int index, int count, float[] pos, Paint paint) { 1579 if (index < 0 || index + count > text.length || count*2 > pos.length) { 1580 throw new IndexOutOfBoundsException(); 1581 } 1582 native_drawPosText(mNativeCanvas, text, index, count, pos, 1583 paint.mNativePaint); 1584 } 1585 1586 /** 1587 * Draw the text in the array, with each character's origin specified by 1588 * the pos array. 1589 * 1590 * This method does not support glyph composition and decomposition and 1591 * should therefore not be used to render complex scripts. 1592 * 1593 * @param text The text to be drawn 1594 * @param pos Array of [x,y] positions, used to position each character 1595 * @param paint The paint used for the text (e.g. color, size, style) 1596 */ 1597 @Deprecated 1598 public void drawPosText(String text, float[] pos, Paint paint) { 1599 if (text.length()*2 > pos.length) { 1600 throw new ArrayIndexOutOfBoundsException(); 1601 } 1602 native_drawPosText(mNativeCanvas, text, pos, paint.mNativePaint); 1603 } 1604 1605 /** 1606 * Draw the text, with origin at (x,y), using the specified paint, along 1607 * the specified path. The paint's Align setting determins where along the 1608 * path to start the text. 1609 * 1610 * @param text The text to be drawn 1611 * @param path The path the text should follow for its baseline 1612 * @param hOffset The distance along the path to add to the text's 1613 * starting position 1614 * @param vOffset The distance above(-) or below(+) the path to position 1615 * the text 1616 * @param paint The paint used for the text (e.g. color, size, style) 1617 */ 1618 public void drawTextOnPath(char[] text, int index, int count, Path path, 1619 float hOffset, float vOffset, Paint paint) { 1620 if (index < 0 || index + count > text.length) { 1621 throw new ArrayIndexOutOfBoundsException(); 1622 } 1623 native_drawTextOnPath(mNativeCanvas, text, index, count, 1624 path.ni(), hOffset, vOffset, 1625 paint.mBidiFlags, paint.mNativePaint); 1626 } 1627 1628 /** 1629 * Draw the text, with origin at (x,y), using the specified paint, along 1630 * the specified path. The paint's Align setting determins where along the 1631 * path to start the text. 1632 * 1633 * @param text The text to be drawn 1634 * @param path The path the text should follow for its baseline 1635 * @param hOffset The distance along the path to add to the text's 1636 * starting position 1637 * @param vOffset The distance above(-) or below(+) the path to position 1638 * the text 1639 * @param paint The paint used for the text (e.g. color, size, style) 1640 */ 1641 public void drawTextOnPath(String text, Path path, float hOffset, float vOffset, Paint paint) { 1642 if (text.length() > 0) { 1643 native_drawTextOnPath(mNativeCanvas, text, path.ni(), hOffset, vOffset, 1644 paint.mBidiFlags, paint.mNativePaint); 1645 } 1646 } 1647 1648 /** 1649 * Save the canvas state, draw the picture, and restore the canvas state. 1650 * This differs from picture.draw(canvas), which does not perform any 1651 * save/restore. 1652 * 1653 * <p> 1654 * <strong>Note:</strong> This forces the picture to internally call 1655 * {@link Picture#endRecording} in order to prepare for playback. 1656 * 1657 * @param picture The picture to be drawn 1658 */ 1659 public void drawPicture(Picture picture) { 1660 picture.endRecording(); 1661 int restoreCount = save(); 1662 picture.draw(this); 1663 restoreToCount(restoreCount); 1664 } 1665 1666 /** 1667 * Draw the picture, stretched to fit into the dst rectangle. 1668 */ 1669 public void drawPicture(Picture picture, RectF dst) { 1670 save(); 1671 translate(dst.left, dst.top); 1672 if (picture.getWidth() > 0 && picture.getHeight() > 0) { 1673 scale(dst.width() / picture.getWidth(), dst.height() / picture.getHeight()); 1674 } 1675 drawPicture(picture); 1676 restore(); 1677 } 1678 1679 /** 1680 * Draw the picture, stretched to fit into the dst rectangle. 1681 */ 1682 public void drawPicture(Picture picture, Rect dst) { 1683 save(); 1684 translate(dst.left, dst.top); 1685 if (picture.getWidth() > 0 && picture.getHeight() > 0) { 1686 scale((float) dst.width() / picture.getWidth(), 1687 (float) dst.height() / picture.getHeight()); 1688 } 1689 drawPicture(picture); 1690 restore(); 1691 } 1692 1693 /** 1694 * Releases the resources associated with this canvas. 1695 * 1696 * @hide 1697 */ 1698 public void release() { 1699 mFinalizer.dispose(); 1700 } 1701 1702 /** 1703 * Free up as much memory as possible from private caches (e.g. fonts, images) 1704 * 1705 * @hide 1706 */ 1707 public static native void freeCaches(); 1708 1709 /** 1710 * Free up text layout caches 1711 * 1712 * @hide 1713 */ 1714 public static native void freeTextLayoutCaches(); 1715 1716 private static native int initRaster(int nativeBitmapOrZero); 1717 private static native void copyNativeCanvasState(int srcCanvas, int dstCanvas); 1718 private static native int native_saveLayer(int nativeCanvas, RectF bounds, 1719 int paint, int layerFlags); 1720 private static native int native_saveLayer(int nativeCanvas, float l, 1721 float t, float r, float b, 1722 int paint, int layerFlags); 1723 private static native int native_saveLayerAlpha(int nativeCanvas, 1724 RectF bounds, int alpha, 1725 int layerFlags); 1726 private static native int native_saveLayerAlpha(int nativeCanvas, float l, 1727 float t, float r, float b, 1728 int alpha, int layerFlags); 1729 1730 private static native void native_concat(int nCanvas, int nMatrix); 1731 private static native void native_setMatrix(int nCanvas, int nMatrix); 1732 private static native boolean native_clipRect(int nCanvas, 1733 float left, float top, 1734 float right, float bottom, 1735 int regionOp); 1736 private static native boolean native_clipPath(int nativeCanvas, 1737 int nativePath, 1738 int regionOp); 1739 private static native boolean native_clipRegion(int nativeCanvas, 1740 int nativeRegion, 1741 int regionOp); 1742 private static native void nativeSetDrawFilter(int nativeCanvas, 1743 int nativeFilter); 1744 private static native boolean native_getClipBounds(int nativeCanvas, 1745 Rect bounds); 1746 private static native void native_getCTM(int canvas, int matrix); 1747 private static native boolean native_quickReject(int nativeCanvas, 1748 RectF rect); 1749 private static native boolean native_quickReject(int nativeCanvas, 1750 int path); 1751 private static native boolean native_quickReject(int nativeCanvas, 1752 float left, float top, 1753 float right, float bottom); 1754 private static native void native_drawRGB(int nativeCanvas, int r, int g, 1755 int b); 1756 private static native void native_drawARGB(int nativeCanvas, int a, int r, 1757 int g, int b); 1758 private static native void native_drawColor(int nativeCanvas, int color); 1759 private static native void native_drawColor(int nativeCanvas, int color, 1760 int mode); 1761 private static native void native_drawPaint(int nativeCanvas, int paint); 1762 private static native void native_drawLine(int nativeCanvas, float startX, 1763 float startY, float stopX, 1764 float stopY, int paint); 1765 private static native void native_drawRect(int nativeCanvas, RectF rect, 1766 int paint); 1767 private static native void native_drawRect(int nativeCanvas, float left, 1768 float top, float right, 1769 float bottom, int paint); 1770 private static native void native_drawOval(int nativeCanvas, RectF oval, 1771 int paint); 1772 private static native void native_drawCircle(int nativeCanvas, float cx, 1773 float cy, float radius, 1774 int paint); 1775 private static native void native_drawArc(int nativeCanvas, RectF oval, 1776 float startAngle, float sweep, 1777 boolean useCenter, int paint); 1778 private static native void native_drawRoundRect(int nativeCanvas, 1779 RectF rect, float rx, 1780 float ry, int paint); 1781 private static native void native_drawPath(int nativeCanvas, int path, 1782 int paint); 1783 private native void native_drawBitmap(int nativeCanvas, int bitmap, 1784 float left, float top, 1785 int nativePaintOrZero, 1786 int canvasDensity, 1787 int screenDensity, 1788 int bitmapDensity); 1789 private native void native_drawBitmap(int nativeCanvas, int bitmap, 1790 Rect src, RectF dst, 1791 int nativePaintOrZero, 1792 int screenDensity, 1793 int bitmapDensity); 1794 private static native void native_drawBitmap(int nativeCanvas, int bitmap, 1795 Rect src, Rect dst, 1796 int nativePaintOrZero, 1797 int screenDensity, 1798 int bitmapDensity); 1799 private static native void native_drawBitmap(int nativeCanvas, int[] colors, 1800 int offset, int stride, float x, 1801 float y, int width, int height, 1802 boolean hasAlpha, 1803 int nativePaintOrZero); 1804 private static native void nativeDrawBitmapMatrix(int nCanvas, int nBitmap, 1805 int nMatrix, int nPaint); 1806 private static native void nativeDrawBitmapMesh(int nCanvas, int nBitmap, 1807 int meshWidth, int meshHeight, 1808 float[] verts, int vertOffset, 1809 int[] colors, int colorOffset, int nPaint); 1810 private static native void nativeDrawVertices(int nCanvas, int mode, int n, 1811 float[] verts, int vertOffset, float[] texs, int texOffset, 1812 int[] colors, int colorOffset, short[] indices, 1813 int indexOffset, int indexCount, int nPaint); 1814 1815 private static native void native_drawText(int nativeCanvas, char[] text, 1816 int index, int count, float x, 1817 float y, int flags, int paint); 1818 private static native void native_drawText(int nativeCanvas, String text, 1819 int start, int end, float x, 1820 float y, int flags, int paint); 1821 1822 private static native void native_drawTextRun(int nativeCanvas, String text, 1823 int start, int end, int contextStart, int contextEnd, 1824 float x, float y, int flags, int paint); 1825 1826 private static native void native_drawTextRun(int nativeCanvas, char[] text, 1827 int start, int count, int contextStart, int contextCount, 1828 float x, float y, int flags, int paint); 1829 1830 private static native void native_drawPosText(int nativeCanvas, 1831 char[] text, int index, 1832 int count, float[] pos, 1833 int paint); 1834 private static native void native_drawPosText(int nativeCanvas, 1835 String text, float[] pos, 1836 int paint); 1837 private static native void native_drawTextOnPath(int nativeCanvas, 1838 char[] text, int index, 1839 int count, int path, 1840 float hOffset, 1841 float vOffset, int bidiFlags, 1842 int paint); 1843 private static native void native_drawTextOnPath(int nativeCanvas, 1844 String text, int path, 1845 float hOffset, 1846 float vOffset, 1847 int flags, int paint); 1848 private static native void finalizer(int nativeCanvas); 1849 } 1850