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