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