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