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