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