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