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