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