Canvas.java revision 876d56612ab8ec7032f702905d694670e6c4febd
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 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 659 public void getMatrix(@NonNull Matrix ctm) { 660 native_getCTM(mNativeCanvasWrapper, ctm.native_instance); 661 } 662 663 /** 664 * Return a new matrix with a copy of the canvas' current transformation 665 * matrix. 666 */ 667 @Deprecated 668 public final @NonNull Matrix getMatrix() { 669 Matrix m = new Matrix(); 670 //noinspection deprecation 671 getMatrix(m); 672 return m; 673 } 674 675 /** 676 * Modify the current clip with the specified rectangle. 677 * 678 * @param rect The rect to intersect with the current clip 679 * @param op How the clip is modified 680 * @return true if the resulting clip is non-empty 681 */ 682 public boolean clipRect(@NonNull RectF rect, @NonNull Region.Op op) { 683 return native_clipRect(mNativeCanvasWrapper, rect.left, rect.top, rect.right, rect.bottom, 684 op.nativeInt); 685 } 686 687 /** 688 * Modify the current clip with the specified rectangle, which is 689 * expressed in local coordinates. 690 * 691 * @param rect The rectangle 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 Rect 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 * Intersect 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 * @return true if the resulting clip is non-empty 706 */ 707 public boolean clipRect(@NonNull RectF rect) { 708 return native_clipRect(mNativeCanvasWrapper, rect.left, rect.top, rect.right, rect.bottom, 709 Region.Op.INTERSECT.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 Rect rect) { 720 return native_clipRect(mNativeCanvasWrapper, rect.left, rect.top, rect.right, rect.bottom, 721 Region.Op.INTERSECT.nativeInt); 722 } 723 724 /** 725 * Modify the current clip with the specified rectangle, which is 726 * expressed in local coordinates. 727 * 728 * @param left The left side of the rectangle to intersect with the 729 * current clip 730 * @param top The top of the rectangle to intersect with the current 731 * clip 732 * @param right The right side of the rectangle to intersect with the 733 * current clip 734 * @param bottom The bottom of the rectangle to intersect with the current 735 * clip 736 * @param op How the clip is modified 737 * @return true if the resulting clip is non-empty 738 */ 739 public boolean clipRect(float left, float top, float right, float bottom, 740 @NonNull Region.Op op) { 741 return native_clipRect(mNativeCanvasWrapper, left, top, right, bottom, op.nativeInt); 742 } 743 744 /** 745 * Intersect the current clip with the specified rectangle, which is 746 * expressed in local coordinates. 747 * 748 * @param left The left side of the rectangle to intersect with the 749 * current clip 750 * @param top The top of the rectangle to intersect with the current clip 751 * @param right The right side of the rectangle to intersect with the 752 * current clip 753 * @param bottom The bottom of the rectangle to intersect with the current 754 * clip 755 * @return true if the resulting clip is non-empty 756 */ 757 public boolean clipRect(float left, float top, float right, float bottom) { 758 return native_clipRect(mNativeCanvasWrapper, left, top, right, bottom, 759 Region.Op.INTERSECT.nativeInt); 760 } 761 762 /** 763 * Intersect the current clip with the specified rectangle, which is 764 * expressed in local coordinates. 765 * 766 * @param left The left side of the rectangle to intersect with the 767 * current clip 768 * @param top The top of the rectangle to intersect with the current clip 769 * @param right The right side of the rectangle to intersect with the 770 * current clip 771 * @param bottom The bottom of the rectangle to intersect with the current 772 * clip 773 * @return true if the resulting clip is non-empty 774 */ 775 public boolean clipRect(int left, int top, int right, int bottom) { 776 return native_clipRect(mNativeCanvasWrapper, left, top, right, bottom, 777 Region.Op.INTERSECT.nativeInt); 778 } 779 780 /** 781 * Modify the current clip with the specified path. 782 * 783 * @param path The path to operate on the current clip 784 * @param op How the clip is modified 785 * @return true if the resulting is non-empty 786 */ 787 public boolean clipPath(@NonNull Path path, @NonNull Region.Op op) { 788 return native_clipPath(mNativeCanvasWrapper, path.ni(), op.nativeInt); 789 } 790 791 /** 792 * Intersect the current clip with the specified path. 793 * 794 * @param path The path to intersect with the current clip 795 * @return true if the resulting is non-empty 796 */ 797 public boolean clipPath(@NonNull Path path) { 798 return clipPath(path, Region.Op.INTERSECT); 799 } 800 801 /** 802 * Modify the current clip with the specified region. Note that unlike 803 * clipRect() and clipPath() which transform their arguments by the 804 * current matrix, clipRegion() assumes its argument is already in the 805 * coordinate system of the current layer's bitmap, and so not 806 * transformation is performed. 807 * 808 * @param region The region to operate on the current clip, based on op 809 * @param op How the clip is modified 810 * @return true if the resulting is non-empty 811 * 812 * @deprecated Unlike all other clip calls this API does not respect the 813 * current matrix. Use {@link #clipRect(Rect)} as an alternative. 814 */ 815 public boolean clipRegion(@NonNull Region region, @NonNull Region.Op op) { 816 return native_clipRegion(mNativeCanvasWrapper, region.ni(), op.nativeInt); 817 } 818 819 /** 820 * Intersect the current clip with the specified region. Note that unlike 821 * clipRect() and clipPath() which transform their arguments by the 822 * current matrix, clipRegion() assumes its argument is already in the 823 * coordinate system of the current layer's bitmap, and so not 824 * transformation is performed. 825 * 826 * @param region The region to operate on the current clip, based on op 827 * @return true if the resulting is non-empty 828 * 829 * @deprecated Unlike all other clip calls this API does not respect the 830 * current matrix. Use {@link #clipRect(Rect)} as an alternative. 831 */ 832 public boolean clipRegion(@NonNull Region region) { 833 return clipRegion(region, Region.Op.INTERSECT); 834 } 835 836 public @Nullable DrawFilter getDrawFilter() { 837 return mDrawFilter; 838 } 839 840 public void setDrawFilter(@Nullable DrawFilter filter) { 841 long nativeFilter = 0; 842 if (filter != null) { 843 nativeFilter = filter.mNativeInt; 844 } 845 mDrawFilter = filter; 846 nativeSetDrawFilter(mNativeCanvasWrapper, nativeFilter); 847 } 848 849 public enum EdgeType { 850 851 /** 852 * Black-and-White: Treat edges by just rounding to nearest pixel boundary 853 */ 854 BW(0), //!< treat edges by just rounding to nearest pixel boundary 855 856 /** 857 * Antialiased: Treat edges by rounding-out, since they may be antialiased 858 */ 859 AA(1); 860 861 EdgeType(int nativeInt) { 862 this.nativeInt = nativeInt; 863 } 864 865 /** 866 * @hide 867 */ 868 public final int nativeInt; 869 } 870 871 /** 872 * Return true if the specified rectangle, after being transformed by the 873 * current matrix, would lie completely outside of the current clip. Call 874 * this to check if an area you intend to draw into is clipped out (and 875 * therefore you can skip making the draw calls). 876 * 877 * @param rect the rect to compare with the current clip 878 * @param type {@link Canvas.EdgeType#AA} if the path should be considered antialiased, 879 * since that means it may affect a larger area (more pixels) than 880 * non-antialiased ({@link Canvas.EdgeType#BW}). 881 * @return true if the rect (transformed by the canvas' matrix) 882 * does not intersect with the canvas' clip 883 */ 884 public boolean quickReject(@NonNull RectF rect, @NonNull EdgeType type) { 885 return native_quickReject(mNativeCanvasWrapper, 886 rect.left, rect.top, rect.right, rect.bottom); 887 } 888 889 /** 890 * Return true if the specified path, after being transformed by the 891 * current matrix, would lie completely outside of the current clip. Call 892 * this to check if an area you intend to draw into is clipped out (and 893 * therefore you can skip making the draw calls). Note: for speed it may 894 * return false even if the path itself might not intersect the clip 895 * (i.e. the bounds of the path intersects, but the path does not). 896 * 897 * @param path The path to compare with the current clip 898 * @param type {@link Canvas.EdgeType#AA} if the path should be considered antialiased, 899 * since that means it may affect a larger area (more pixels) than 900 * non-antialiased ({@link Canvas.EdgeType#BW}). 901 * @return true if the path (transformed by the canvas' matrix) 902 * does not intersect with the canvas' clip 903 */ 904 public boolean quickReject(@NonNull Path path, @NonNull EdgeType type) { 905 return native_quickReject(mNativeCanvasWrapper, path.ni()); 906 } 907 908 /** 909 * Return true if the specified rectangle, after being transformed by the 910 * current matrix, would lie completely outside of the current clip. Call 911 * this to check if an area you intend to draw into is clipped out (and 912 * therefore you can skip making the draw calls). 913 * 914 * @param left The left side of the rectangle to compare with the 915 * current clip 916 * @param top The top of the rectangle to compare with the current 917 * clip 918 * @param right The right side of the rectangle to compare with the 919 * current clip 920 * @param bottom The bottom of the rectangle to compare with the 921 * current clip 922 * @param type {@link Canvas.EdgeType#AA} if the path should be considered antialiased, 923 * since that means it may affect a larger area (more pixels) than 924 * non-antialiased ({@link Canvas.EdgeType#BW}). 925 * @return true if the rect (transformed by the canvas' matrix) 926 * does not intersect with the canvas' clip 927 */ 928 public boolean quickReject(float left, float top, float right, float bottom, 929 @NonNull EdgeType type) { 930 return native_quickReject(mNativeCanvasWrapper, left, top, right, bottom); 931 } 932 933 /** 934 * Return the bounds of the current clip (in local coordinates) in the 935 * bounds parameter, and return true if it is non-empty. This can be useful 936 * in a way similar to quickReject, in that it tells you that drawing 937 * outside of these bounds will be clipped out. 938 * 939 * @param bounds Return the clip bounds here. If it is null, ignore it but 940 * still return true if the current clip is non-empty. 941 * @return true if the current clip is non-empty. 942 */ 943 public boolean getClipBounds(@Nullable Rect bounds) { 944 return native_getClipBounds(mNativeCanvasWrapper, bounds); 945 } 946 947 /** 948 * Retrieve the bounds of the current clip (in local coordinates). 949 * 950 * @return the clip bounds, or [0, 0, 0, 0] if the clip is empty. 951 */ 952 public final @NonNull Rect getClipBounds() { 953 Rect r = new Rect(); 954 getClipBounds(r); 955 return r; 956 } 957 958 /** 959 * Fill the entire canvas' bitmap (restricted to the current clip) with the 960 * specified RGB color, using srcover porterduff mode. 961 * 962 * @param r red component (0..255) of the color to draw onto the canvas 963 * @param g green component (0..255) of the color to draw onto the canvas 964 * @param b blue component (0..255) of the color to draw onto the canvas 965 */ 966 public void drawRGB(int r, int g, int b) { 967 drawColor(Color.rgb(r, g, b)); 968 } 969 970 /** 971 * Fill the entire canvas' bitmap (restricted to the current clip) with the 972 * specified ARGB color, using srcover porterduff mode. 973 * 974 * @param a alpha component (0..255) of the color to draw onto the canvas 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 drawARGB(int a, int r, int g, int b) { 980 drawColor(Color.argb(a, r, g, b)); 981 } 982 983 /** 984 * Fill the entire canvas' bitmap (restricted to the current clip) with the 985 * specified color, using srcover porterduff mode. 986 * 987 * @param color the color to draw onto the canvas 988 */ 989 public void drawColor(@ColorInt int color) { 990 native_drawColor(mNativeCanvasWrapper, color, PorterDuff.Mode.SRC_OVER.nativeInt); 991 } 992 993 /** 994 * Fill the entire canvas' bitmap (restricted to the current clip) with the 995 * specified color and porter-duff xfermode. 996 * 997 * @param color the color to draw with 998 * @param mode the porter-duff mode to apply to the color 999 */ 1000 public void drawColor(@ColorInt int color, @NonNull PorterDuff.Mode mode) { 1001 native_drawColor(mNativeCanvasWrapper, color, mode.nativeInt); 1002 } 1003 1004 /** 1005 * Fill the entire canvas' bitmap (restricted to the current clip) with 1006 * the specified paint. This is equivalent (but faster) to drawing an 1007 * infinitely large rectangle with the specified paint. 1008 * 1009 * @param paint The paint used to draw onto the canvas 1010 */ 1011 public void drawPaint(@NonNull Paint paint) { 1012 native_drawPaint(mNativeCanvasWrapper, paint.getNativeInstance()); 1013 } 1014 1015 /** 1016 * Draw a series of points. Each point is centered at the coordinate 1017 * specified by pts[], and its diameter is specified by the paint's stroke 1018 * width (as transformed by the canvas' CTM), with special treatment for 1019 * a stroke width of 0, which always draws exactly 1 pixel (or at most 4 1020 * if antialiasing is enabled). The shape of the point is controlled by 1021 * the paint's Cap type. The shape is a square, unless the cap type is 1022 * Round, in which case the shape is a circle. 1023 * 1024 * @param pts Array of points to draw [x0 y0 x1 y1 x2 y2 ...] 1025 * @param offset Number of values to skip before starting to draw. 1026 * @param count The number of values to process, after skipping offset 1027 * of them. Since one point uses two values, the number of 1028 * "points" that are drawn is really (count >> 1). 1029 * @param paint The paint used to draw the points 1030 */ 1031 public void drawPoints(@Size(multiple=2) float[] pts, int offset, int count, 1032 @NonNull Paint paint) { 1033 native_drawPoints(mNativeCanvasWrapper, pts, offset, count, paint.getNativeInstance()); 1034 } 1035 1036 /** 1037 * Helper for drawPoints() that assumes you want to draw the entire array 1038 */ 1039 public void drawPoints(@Size(multiple=2) @NonNull float[] pts, @NonNull Paint paint) { 1040 drawPoints(pts, 0, pts.length, paint); 1041 } 1042 1043 /** 1044 * Helper for drawPoints() for drawing a single point. 1045 */ 1046 public void drawPoint(float x, float y, @NonNull Paint paint) { 1047 native_drawPoint(mNativeCanvasWrapper, x, y, paint.getNativeInstance()); 1048 } 1049 1050 /** 1051 * Draw a line segment with the specified start and stop x,y coordinates, 1052 * using the specified paint. 1053 * 1054 * <p>Note that since a line is always "framed", the Style is ignored in the paint.</p> 1055 * 1056 * <p>Degenerate lines (length is 0) will not be drawn.</p> 1057 * 1058 * @param startX The x-coordinate of the start point of the line 1059 * @param startY The y-coordinate of the start point of the line 1060 * @param paint The paint used to draw the line 1061 */ 1062 public void drawLine(float startX, float startY, float stopX, float stopY, 1063 @NonNull Paint paint) { 1064 native_drawLine(mNativeCanvasWrapper, startX, startY, stopX, stopY, paint.getNativeInstance()); 1065 } 1066 1067 /** 1068 * Draw a series of lines. Each line is taken from 4 consecutive values 1069 * in the pts array. Thus to draw 1 line, the array must contain at least 4 1070 * values. This is logically the same as drawing the array as follows: 1071 * drawLine(pts[0], pts[1], pts[2], pts[3]) followed by 1072 * drawLine(pts[4], pts[5], pts[6], pts[7]) and so on. 1073 * 1074 * @param pts Array of points to draw [x0 y0 x1 y1 x2 y2 ...] 1075 * @param offset Number of values in the array to skip before drawing. 1076 * @param count The number of values in the array to process, after 1077 * skipping "offset" of them. Since each line uses 4 values, 1078 * the number of "lines" that are drawn is really 1079 * (count >> 2). 1080 * @param paint The paint used to draw the points 1081 */ 1082 public void drawLines(@Size(min=4,multiple=2) float[] pts, int offset, int count, Paint paint) { 1083 native_drawLines(mNativeCanvasWrapper, pts, offset, count, paint.getNativeInstance()); 1084 } 1085 1086 public void drawLines(@Size(min=4,multiple=2) @NonNull float[] pts, @NonNull Paint paint) { 1087 drawLines(pts, 0, pts.length, paint); 1088 } 1089 1090 /** 1091 * Draw the specified Rect using the specified paint. The rectangle will 1092 * be filled or framed based on the Style in the paint. 1093 * 1094 * @param rect The rect to be drawn 1095 * @param paint The paint used to draw the rect 1096 */ 1097 public void drawRect(@NonNull RectF rect, @NonNull Paint paint) { 1098 native_drawRect(mNativeCanvasWrapper, 1099 rect.left, rect.top, rect.right, rect.bottom, paint.getNativeInstance()); 1100 } 1101 1102 /** 1103 * Draw the specified Rect using the specified Paint. The rectangle 1104 * will be filled or framed based on the Style in the paint. 1105 * 1106 * @param r The rectangle to be drawn. 1107 * @param paint The paint used to draw the rectangle 1108 */ 1109 public void drawRect(@NonNull Rect r, @NonNull Paint paint) { 1110 drawRect(r.left, r.top, r.right, r.bottom, paint); 1111 } 1112 1113 1114 /** 1115 * Draw the specified Rect using the specified paint. The rectangle will 1116 * be filled or framed based on the Style in the paint. 1117 * 1118 * @param left The left side of the rectangle to be drawn 1119 * @param top The top side of the rectangle to be drawn 1120 * @param right The right side of the rectangle to be drawn 1121 * @param bottom The bottom side of the rectangle to be drawn 1122 * @param paint The paint used to draw the rect 1123 */ 1124 public void drawRect(float left, float top, float right, float bottom, @NonNull Paint paint) { 1125 native_drawRect(mNativeCanvasWrapper, left, top, right, bottom, paint.getNativeInstance()); 1126 } 1127 1128 /** 1129 * Draw the specified oval using the specified paint. The oval will be 1130 * filled or framed based on the Style in the paint. 1131 * 1132 * @param oval The rectangle bounds of the oval to be drawn 1133 */ 1134 public void drawOval(@NonNull RectF oval, @NonNull Paint paint) { 1135 if (oval == null) { 1136 throw new NullPointerException(); 1137 } 1138 drawOval(oval.left, oval.top, oval.right, oval.bottom, paint); 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 public void drawOval(float left, float top, float right, float bottom, @NonNull Paint paint) { 1146 native_drawOval(mNativeCanvasWrapper, left, top, right, bottom, paint.getNativeInstance()); 1147 } 1148 1149 /** 1150 * Draw the specified circle using the specified paint. If radius is <= 0, 1151 * then nothing will be drawn. The circle will be filled or framed based 1152 * on the Style in the paint. 1153 * 1154 * @param cx The x-coordinate of the center of the cirle to be drawn 1155 * @param cy The y-coordinate of the center of the cirle to be drawn 1156 * @param radius The radius of the cirle to be drawn 1157 * @param paint The paint used to draw the circle 1158 */ 1159 public void drawCircle(float cx, float cy, float radius, @NonNull Paint paint) { 1160 native_drawCircle(mNativeCanvasWrapper, cx, cy, radius, paint.getNativeInstance()); 1161 } 1162 1163 /** 1164 * <p>Draw the specified arc, which will be scaled to fit inside the 1165 * specified oval.</p> 1166 * 1167 * <p>If the start angle is negative or >= 360, the start angle is treated 1168 * as start angle modulo 360.</p> 1169 * 1170 * <p>If the sweep angle is >= 360, then the oval is drawn 1171 * completely. Note that this differs slightly from SkPath::arcTo, which 1172 * treats the sweep angle modulo 360. If the sweep angle is negative, 1173 * the sweep angle is treated as sweep angle modulo 360</p> 1174 * 1175 * <p>The arc is drawn clockwise. An angle of 0 degrees correspond to the 1176 * geometric angle of 0 degrees (3 o'clock on a watch.)</p> 1177 * 1178 * @param oval The bounds of oval used to define the shape and size 1179 * of the arc 1180 * @param startAngle Starting angle (in degrees) where the arc begins 1181 * @param sweepAngle Sweep angle (in degrees) measured clockwise 1182 * @param useCenter If true, include the center of the oval in the arc, and 1183 close it if it is being stroked. This will draw a wedge 1184 * @param paint The paint used to draw the arc 1185 */ 1186 public void drawArc(@NonNull RectF oval, float startAngle, float sweepAngle, boolean useCenter, 1187 @NonNull Paint paint) { 1188 drawArc(oval.left, oval.top, oval.right, oval.bottom, startAngle, sweepAngle, useCenter, 1189 paint); 1190 } 1191 1192 /** 1193 * <p>Draw the specified arc, which will be scaled to fit inside the 1194 * specified oval.</p> 1195 * 1196 * <p>If the start angle is negative or >= 360, the start angle is treated 1197 * as start angle modulo 360.</p> 1198 * 1199 * <p>If the sweep angle is >= 360, then the oval is drawn 1200 * completely. Note that this differs slightly from SkPath::arcTo, which 1201 * treats the sweep angle modulo 360. If the sweep angle is negative, 1202 * the sweep angle is treated as sweep angle modulo 360</p> 1203 * 1204 * <p>The arc is drawn clockwise. An angle of 0 degrees correspond to the 1205 * geometric angle of 0 degrees (3 o'clock on a watch.)</p> 1206 * 1207 * @param startAngle Starting angle (in degrees) where the arc begins 1208 * @param sweepAngle Sweep angle (in degrees) measured clockwise 1209 * @param useCenter If true, include the center of the oval in the arc, and 1210 close it if it is being stroked. This will draw a wedge 1211 * @param paint The paint used to draw the arc 1212 */ 1213 public void drawArc(float left, float top, float right, float bottom, float startAngle, 1214 float sweepAngle, boolean useCenter, @NonNull Paint paint) { 1215 native_drawArc(mNativeCanvasWrapper, left, top, right, bottom, startAngle, sweepAngle, 1216 useCenter, paint.getNativeInstance()); 1217 } 1218 1219 /** 1220 * Draw the specified round-rect using the specified paint. The roundrect 1221 * will be filled or framed based on the Style in the paint. 1222 * 1223 * @param rect The rectangular bounds of the roundRect to be drawn 1224 * @param rx The x-radius of the oval used to round the corners 1225 * @param ry The y-radius of the oval used to round the corners 1226 * @param paint The paint used to draw the roundRect 1227 */ 1228 public void drawRoundRect(@NonNull RectF rect, float rx, float ry, @NonNull Paint paint) { 1229 drawRoundRect(rect.left, rect.top, rect.right, rect.bottom, rx, ry, paint); 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 rx The x-radius of the oval used to round the corners 1237 * @param ry The y-radius of the oval used to round the corners 1238 * @param paint The paint used to draw the roundRect 1239 */ 1240 public void drawRoundRect(float left, float top, float right, float bottom, float rx, float ry, 1241 @NonNull Paint paint) { 1242 native_drawRoundRect(mNativeCanvasWrapper, left, top, right, bottom, rx, ry, paint.getNativeInstance()); 1243 } 1244 1245 /** 1246 * Draw the specified path using the specified paint. The path will be 1247 * filled or framed based on the Style in the paint. 1248 * 1249 * @param path The path to be drawn 1250 * @param paint The paint used to draw the path 1251 */ 1252 public void drawPath(@NonNull Path path, @NonNull Paint paint) { 1253 if (path.isSimplePath && path.rects != null) { 1254 native_drawRegion(mNativeCanvasWrapper, path.rects.mNativeRegion, paint.getNativeInstance()); 1255 } else { 1256 native_drawPath(mNativeCanvasWrapper, path.ni(), paint.getNativeInstance()); 1257 } 1258 } 1259 1260 /** 1261 * @hide 1262 */ 1263 protected static void throwIfCannotDraw(Bitmap bitmap) { 1264 if (bitmap.isRecycled()) { 1265 throw new RuntimeException("Canvas: trying to use a recycled bitmap " + bitmap); 1266 } 1267 if (!bitmap.isPremultiplied() && bitmap.getConfig() == Bitmap.Config.ARGB_8888 && 1268 bitmap.hasAlpha()) { 1269 throw new RuntimeException("Canvas: trying to use a non-premultiplied bitmap " 1270 + bitmap); 1271 } 1272 } 1273 1274 /** 1275 * Draws the specified bitmap as an N-patch (most often, a 9-patches.) 1276 * 1277 * @param patch The ninepatch object to render 1278 * @param dst The destination rectangle. 1279 * @param paint The paint to draw the bitmap with. may be null 1280 * 1281 * @hide 1282 */ 1283 public void drawPatch(@NonNull NinePatch patch, @NonNull Rect dst, @Nullable Paint paint) { 1284 patch.drawSoftware(this, dst, paint); 1285 } 1286 1287 /** 1288 * Draws the specified bitmap as an N-patch (most often, a 9-patches.) 1289 * 1290 * @param patch The ninepatch object to render 1291 * @param dst The destination rectangle. 1292 * @param paint The paint to draw the bitmap with. may be null 1293 * 1294 * @hide 1295 */ 1296 public void drawPatch(@NonNull NinePatch patch, @NonNull RectF dst, @Nullable Paint paint) { 1297 patch.drawSoftware(this, dst, paint); 1298 } 1299 1300 /** 1301 * Draw the specified bitmap, with its top/left corner at (x,y), using 1302 * the specified paint, transformed by the current matrix. 1303 * 1304 * <p>Note: if the paint contains a maskfilter that generates a mask which 1305 * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter), 1306 * then the bitmap will be drawn as if it were in a Shader with CLAMP mode. 1307 * Thus the color outside of the original width/height will be the edge 1308 * color replicated. 1309 * 1310 * <p>If the bitmap and canvas have different densities, this function 1311 * will take care of automatically scaling the bitmap to draw at the 1312 * same density as the canvas. 1313 * 1314 * @param bitmap The bitmap to be drawn 1315 * @param left The position of the left side of the bitmap being drawn 1316 * @param top The position of the top side of the bitmap being drawn 1317 * @param paint The paint used to draw the bitmap (may be null) 1318 */ 1319 public void drawBitmap(@NonNull Bitmap bitmap, float left, float top, @Nullable Paint paint) { 1320 throwIfCannotDraw(bitmap); 1321 native_drawBitmap(mNativeCanvasWrapper, bitmap, left, top, 1322 paint != null ? paint.getNativeInstance() : 0, mDensity, mScreenDensity, bitmap.mDensity); 1323 } 1324 1325 /** 1326 * Draw the specified bitmap, scaling/translating automatically to fill 1327 * the destination rectangle. If the source rectangle is not null, it 1328 * specifies the subset of the bitmap to draw. 1329 * 1330 * <p>Note: if the paint contains a maskfilter that generates a mask which 1331 * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter), 1332 * then the bitmap will be drawn as if it were in a Shader with CLAMP mode. 1333 * Thus the color outside of the original width/height will be the edge 1334 * color replicated. 1335 * 1336 * <p>This function <em>ignores the density associated with the bitmap</em>. 1337 * This is because the source and destination rectangle coordinate 1338 * spaces are in their respective densities, so must already have the 1339 * appropriate scaling factor applied. 1340 * 1341 * @param bitmap The bitmap to be drawn 1342 * @param src May be null. The subset of the bitmap to be drawn 1343 * @param dst The rectangle that the bitmap will be scaled/translated 1344 * to fit into 1345 * @param paint May be null. The paint used to draw the bitmap 1346 */ 1347 public void drawBitmap(@NonNull Bitmap bitmap, @Nullable Rect src, @NonNull RectF dst, 1348 @Nullable Paint paint) { 1349 if (dst == null) { 1350 throw new NullPointerException(); 1351 } 1352 throwIfCannotDraw(bitmap); 1353 final long nativePaint = paint == null ? 0 : paint.getNativeInstance(); 1354 1355 float left, top, right, bottom; 1356 if (src == null) { 1357 left = top = 0; 1358 right = bitmap.getWidth(); 1359 bottom = bitmap.getHeight(); 1360 } else { 1361 left = src.left; 1362 right = src.right; 1363 top = src.top; 1364 bottom = src.bottom; 1365 } 1366 1367 native_drawBitmap(mNativeCanvasWrapper, bitmap, left, top, right, bottom, 1368 dst.left, dst.top, dst.right, dst.bottom, nativePaint, mScreenDensity, 1369 bitmap.mDensity); 1370 } 1371 1372 /** 1373 * Draw the specified bitmap, scaling/translating automatically to fill 1374 * the destination rectangle. If the source rectangle is not null, it 1375 * specifies the subset of the bitmap to draw. 1376 * 1377 * <p>Note: if the paint contains a maskfilter that generates a mask which 1378 * extends beyond the bitmap's original width/height (e.g. BlurMaskFilter), 1379 * then the bitmap will be drawn as if it were in a Shader with CLAMP mode. 1380 * Thus the color outside of the original width/height will be the edge 1381 * color replicated. 1382 * 1383 * <p>This function <em>ignores the density associated with the bitmap</em>. 1384 * This is because the source and destination rectangle coordinate 1385 * spaces are in their respective densities, so must already have the 1386 * appropriate scaling factor applied. 1387 * 1388 * @param bitmap The bitmap to be drawn 1389 * @param src May be null. The subset of the bitmap to be drawn 1390 * @param dst The rectangle that the bitmap will be scaled/translated 1391 * to fit into 1392 * @param paint May be null. The paint used to draw the bitmap 1393 */ 1394 public void drawBitmap(@NonNull Bitmap bitmap, @Nullable Rect src, @NonNull Rect dst, 1395 @Nullable Paint paint) { 1396 if (dst == null) { 1397 throw new NullPointerException(); 1398 } 1399 throwIfCannotDraw(bitmap); 1400 final long nativePaint = paint == null ? 0 : paint.getNativeInstance(); 1401 1402 int left, top, right, bottom; 1403 if (src == null) { 1404 left = top = 0; 1405 right = bitmap.getWidth(); 1406 bottom = bitmap.getHeight(); 1407 } else { 1408 left = src.left; 1409 right = src.right; 1410 top = src.top; 1411 bottom = src.bottom; 1412 } 1413 1414 native_drawBitmap(mNativeCanvasWrapper, bitmap, left, top, right, bottom, 1415 dst.left, dst.top, dst.right, dst.bottom, nativePaint, mScreenDensity, 1416 bitmap.mDensity); 1417 } 1418 1419 /** 1420 * Treat the specified array of colors as a bitmap, and draw it. This gives 1421 * the same result as first creating a bitmap from the array, and then 1422 * drawing it, but this method avoids explicitly creating a bitmap object 1423 * which can be more efficient if the colors are changing often. 1424 * 1425 * @param colors Array of colors representing the pixels of the bitmap 1426 * @param offset Offset into the array of colors for the first pixel 1427 * @param stride The number of colors in the array between rows (must be 1428 * >= width or <= -width). 1429 * @param x The X coordinate for where to draw the bitmap 1430 * @param y The Y coordinate for where to draw the bitmap 1431 * @param width The width of the bitmap 1432 * @param height The height of the bitmap 1433 * @param hasAlpha True if the alpha channel of the colors contains valid 1434 * values. If false, the alpha byte is ignored (assumed to 1435 * be 0xFF for every pixel). 1436 * @param paint May be null. The paint used to draw the bitmap 1437 * 1438 * @deprecated Usage with a {@link #isHardwareAccelerated() hardware accelerated} canvas 1439 * requires an internal copy of color buffer contents every time this method is called. Using a 1440 * Bitmap avoids this copy, and allows the application to more explicitly control the lifetime 1441 * and copies of pixel data. 1442 */ 1443 @Deprecated 1444 public void drawBitmap(@NonNull int[] colors, int offset, int stride, float x, float y, 1445 int width, int height, boolean hasAlpha, @Nullable Paint paint) { 1446 // check for valid input 1447 if (width < 0) { 1448 throw new IllegalArgumentException("width must be >= 0"); 1449 } 1450 if (height < 0) { 1451 throw new IllegalArgumentException("height must be >= 0"); 1452 } 1453 if (Math.abs(stride) < width) { 1454 throw new IllegalArgumentException("abs(stride) must be >= width"); 1455 } 1456 int lastScanline = offset + (height - 1) * stride; 1457 int length = colors.length; 1458 if (offset < 0 || (offset + width > length) || lastScanline < 0 1459 || (lastScanline + width > length)) { 1460 throw new ArrayIndexOutOfBoundsException(); 1461 } 1462 // quick escape if there's nothing to draw 1463 if (width == 0 || height == 0) { 1464 return; 1465 } 1466 // punch down to native for the actual draw 1467 native_drawBitmap(mNativeCanvasWrapper, colors, offset, stride, x, y, width, height, hasAlpha, 1468 paint != null ? paint.getNativeInstance() : 0); 1469 } 1470 1471 /** 1472 * Legacy version of drawBitmap(int[] colors, ...) that took ints for x,y 1473 * 1474 * @deprecated Usage with a {@link #isHardwareAccelerated() hardware accelerated} canvas 1475 * requires an internal copy of color buffer contents every time this method is called. Using a 1476 * Bitmap avoids this copy, and allows the application to more explicitly control the lifetime 1477 * and copies of pixel data. 1478 */ 1479 @Deprecated 1480 public void drawBitmap(@NonNull int[] colors, int offset, int stride, int x, int y, 1481 int width, int height, boolean hasAlpha, @Nullable Paint paint) { 1482 // call through to the common float version 1483 drawBitmap(colors, offset, stride, (float)x, (float)y, width, height, 1484 hasAlpha, paint); 1485 } 1486 1487 /** 1488 * Draw the bitmap using the specified matrix. 1489 * 1490 * @param bitmap The bitmap to draw 1491 * @param matrix The matrix used to transform the bitmap when it is drawn 1492 * @param paint May be null. The paint used to draw the bitmap 1493 */ 1494 public void drawBitmap(@NonNull Bitmap bitmap, @NonNull Matrix matrix, @Nullable Paint paint) { 1495 nativeDrawBitmapMatrix(mNativeCanvasWrapper, bitmap, matrix.ni(), 1496 paint != null ? paint.getNativeInstance() : 0); 1497 } 1498 1499 /** 1500 * @hide 1501 */ 1502 protected static void checkRange(int length, int offset, int count) { 1503 if ((offset | count) < 0 || offset + count > length) { 1504 throw new ArrayIndexOutOfBoundsException(); 1505 } 1506 } 1507 1508 /** 1509 * Draw the bitmap through the mesh, where mesh vertices are evenly 1510 * distributed across the bitmap. There are meshWidth+1 vertices across, and 1511 * meshHeight+1 vertices down. The verts array is accessed in row-major 1512 * order, so that the first meshWidth+1 vertices are distributed across the 1513 * top of the bitmap from left to right. A more general version of this 1514 * method is drawVertices(). 1515 * 1516 * @param bitmap The bitmap to draw using the mesh 1517 * @param meshWidth The number of columns in the mesh. Nothing is drawn if 1518 * this is 0 1519 * @param meshHeight The number of rows in the mesh. Nothing is drawn if 1520 * this is 0 1521 * @param verts Array of x,y pairs, specifying where the mesh should be 1522 * drawn. There must be at least 1523 * (meshWidth+1) * (meshHeight+1) * 2 + vertOffset values 1524 * in the array 1525 * @param vertOffset Number of verts elements to skip before drawing 1526 * @param colors May be null. Specifies a color at each vertex, which is 1527 * interpolated across the cell, and whose values are 1528 * multiplied by the corresponding bitmap colors. If not null, 1529 * there must be at least (meshWidth+1) * (meshHeight+1) + 1530 * colorOffset values in the array. 1531 * @param colorOffset Number of color elements to skip before drawing 1532 * @param paint May be null. The paint used to draw the bitmap 1533 */ 1534 public void drawBitmapMesh(@NonNull Bitmap bitmap, int meshWidth, int meshHeight, 1535 @NonNull float[] verts, int vertOffset, @Nullable int[] colors, int colorOffset, 1536 @Nullable Paint paint) { 1537 if ((meshWidth | meshHeight | vertOffset | colorOffset) < 0) { 1538 throw new ArrayIndexOutOfBoundsException(); 1539 } 1540 if (meshWidth == 0 || meshHeight == 0) { 1541 return; 1542 } 1543 int count = (meshWidth + 1) * (meshHeight + 1); 1544 // we mul by 2 since we need two floats per vertex 1545 checkRange(verts.length, vertOffset, count * 2); 1546 if (colors != null) { 1547 // no mul by 2, since we need only 1 color per vertex 1548 checkRange(colors.length, colorOffset, count); 1549 } 1550 nativeDrawBitmapMesh(mNativeCanvasWrapper, bitmap, meshWidth, meshHeight, 1551 verts, vertOffset, colors, colorOffset, 1552 paint != null ? paint.getNativeInstance() : 0); 1553 } 1554 1555 public enum VertexMode { 1556 TRIANGLES(0), 1557 TRIANGLE_STRIP(1), 1558 TRIANGLE_FAN(2); 1559 1560 VertexMode(int nativeInt) { 1561 this.nativeInt = nativeInt; 1562 } 1563 1564 /** 1565 * @hide 1566 */ 1567 public final int nativeInt; 1568 } 1569 1570 /** 1571 * Draw the array of vertices, interpreted as triangles (based on mode). The 1572 * verts array is required, and specifies the x,y pairs for each vertex. If 1573 * texs is non-null, then it is used to specify the coordinate in shader 1574 * coordinates to use at each vertex (the paint must have a shader in this 1575 * case). If there is no texs array, but there is a color array, then each 1576 * color is interpolated across its corresponding triangle in a gradient. If 1577 * both texs and colors arrays are present, then they behave as before, but 1578 * the resulting color at each pixels is the result of multiplying the 1579 * colors from the shader and the color-gradient together. The indices array 1580 * is optional, but if it is present, then it is used to specify the index 1581 * of each triangle, rather than just walking through the arrays in order. 1582 * 1583 * @param mode How to interpret the array of vertices 1584 * @param vertexCount The number of values in the vertices array (and 1585 * corresponding texs and colors arrays if non-null). Each logical 1586 * vertex is two values (x, y), vertexCount must be a multiple of 2. 1587 * @param verts Array of vertices for the mesh 1588 * @param vertOffset Number of values in the verts to skip before drawing. 1589 * @param texs May be null. If not null, specifies the coordinates to sample 1590 * into the current shader (e.g. bitmap tile or gradient) 1591 * @param texOffset Number of values in texs to skip before drawing. 1592 * @param colors May be null. If not null, specifies a color for each 1593 * vertex, to be interpolated across the triangle. 1594 * @param colorOffset Number of values in colors to skip before drawing. 1595 * @param indices If not null, array of indices to reference into the 1596 * vertex (texs, colors) array. 1597 * @param indexCount number of entries in the indices array (if not null). 1598 * @param paint Specifies the shader to use if the texs array is non-null. 1599 */ 1600 public void drawVertices(@NonNull VertexMode mode, int vertexCount, @NonNull float[] verts, 1601 int vertOffset, @Nullable float[] texs, int texOffset, @Nullable int[] colors, 1602 int colorOffset, @Nullable short[] indices, int indexOffset, int indexCount, 1603 @NonNull Paint paint) { 1604 checkRange(verts.length, vertOffset, vertexCount); 1605 if (isHardwareAccelerated()) { 1606 return; 1607 } 1608 if (texs != null) { 1609 checkRange(texs.length, texOffset, vertexCount); 1610 } 1611 if (colors != null) { 1612 checkRange(colors.length, colorOffset, vertexCount / 2); 1613 } 1614 if (indices != null) { 1615 checkRange(indices.length, indexOffset, indexCount); 1616 } 1617 nativeDrawVertices(mNativeCanvasWrapper, mode.nativeInt, vertexCount, verts, 1618 vertOffset, texs, texOffset, colors, colorOffset, 1619 indices, indexOffset, indexCount, paint.getNativeInstance()); 1620 } 1621 1622 /** 1623 * Draw the text, with origin at (x,y), using the specified paint. The 1624 * origin is interpreted based on the Align setting in the paint. 1625 * 1626 * @param text The text to be drawn 1627 * @param x The x-coordinate of the origin of the text being drawn 1628 * @param y The y-coordinate of the baseline of the text being drawn 1629 * @param paint The paint used for the text (e.g. color, size, style) 1630 */ 1631 public void drawText(@NonNull char[] text, int index, int count, float x, float y, 1632 @NonNull Paint paint) { 1633 if ((index | count | (index + count) | 1634 (text.length - index - count)) < 0) { 1635 throw new IndexOutOfBoundsException(); 1636 } 1637 native_drawText(mNativeCanvasWrapper, text, index, count, x, y, paint.mBidiFlags, 1638 paint.getNativeInstance(), paint.mNativeTypeface); 1639 } 1640 1641 /** 1642 * Draw the text, with origin at (x,y), using the specified paint. The 1643 * origin is interpreted based on the Align setting in the paint. 1644 * 1645 * @param text The text to be drawn 1646 * @param x The x-coordinate of the origin of the text being drawn 1647 * @param y The y-coordinate of the baseline of the text being drawn 1648 * @param paint The paint used for the text (e.g. color, size, style) 1649 */ 1650 public void drawText(@NonNull String text, float x, float y, @NonNull Paint paint) { 1651 native_drawText(mNativeCanvasWrapper, text, 0, text.length(), x, y, paint.mBidiFlags, 1652 paint.getNativeInstance(), paint.mNativeTypeface); 1653 } 1654 1655 /** 1656 * Draw the text, with origin at (x,y), using the specified paint. 1657 * The origin is interpreted based on the Align setting in the paint. 1658 * 1659 * @param text The text to be drawn 1660 * @param start The index of the first character in text to draw 1661 * @param end (end - 1) is the index of the last character in text to draw 1662 * @param x The x-coordinate of the origin of the text being drawn 1663 * @param y The y-coordinate of the baseline of the text being drawn 1664 * @param paint The paint used for the text (e.g. color, size, style) 1665 */ 1666 public void drawText(@NonNull String text, int start, int end, float x, float y, 1667 @NonNull Paint paint) { 1668 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1669 throw new IndexOutOfBoundsException(); 1670 } 1671 native_drawText(mNativeCanvasWrapper, text, start, end, x, y, paint.mBidiFlags, 1672 paint.getNativeInstance(), paint.mNativeTypeface); 1673 } 1674 1675 /** 1676 * Draw the specified range of text, specified by start/end, with its 1677 * origin at (x,y), in the specified Paint. The origin is interpreted 1678 * based on the Align setting in the Paint. 1679 * 1680 * @param text The text to be drawn 1681 * @param start The index of the first character in text to draw 1682 * @param end (end - 1) is the index of the last character in text 1683 * to draw 1684 * @param x The x-coordinate of origin for where to draw the text 1685 * @param y The y-coordinate of origin for where to draw the text 1686 * @param paint The paint used for the text (e.g. color, size, style) 1687 */ 1688 public void drawText(@NonNull CharSequence text, int start, int end, float x, float y, 1689 @NonNull Paint paint) { 1690 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1691 throw new IndexOutOfBoundsException(); 1692 } 1693 if (text instanceof String || text instanceof SpannedString || 1694 text instanceof SpannableString) { 1695 native_drawText(mNativeCanvasWrapper, text.toString(), start, end, x, y, 1696 paint.mBidiFlags, paint.getNativeInstance(), paint.mNativeTypeface); 1697 } else if (text instanceof GraphicsOperations) { 1698 ((GraphicsOperations) text).drawText(this, start, end, x, y, 1699 paint); 1700 } else { 1701 char[] buf = TemporaryBuffer.obtain(end - start); 1702 TextUtils.getChars(text, start, end, buf, 0); 1703 native_drawText(mNativeCanvasWrapper, buf, 0, end - start, x, y, 1704 paint.mBidiFlags, paint.getNativeInstance(), paint.mNativeTypeface); 1705 TemporaryBuffer.recycle(buf); 1706 } 1707 } 1708 1709 /** 1710 * Draw a run of text, all in a single direction, with optional context for complex text 1711 * shaping. 1712 * 1713 * <p>See {@link #drawTextRun(CharSequence, int, int, int, int, float, float, boolean, Paint)} 1714 * for more details. This method uses a character array rather than CharSequence to 1715 * represent the string. Also, to be consistent with the pattern established in 1716 * {@link #drawText}, in this method {@code count} and {@code contextCount} are used rather 1717 * than offsets of the end position; {@code count = end - start, contextCount = contextEnd - 1718 * contextStart}. 1719 * 1720 * @param text the text to render 1721 * @param index the start of the text to render 1722 * @param count the count of chars to render 1723 * @param contextIndex the start of the context for shaping. Must be 1724 * no greater than index. 1725 * @param contextCount the number of characters in the context for shaping. 1726 * contexIndex + contextCount must be no less than index + count. 1727 * @param x the x position at which to draw the text 1728 * @param y the y position at which to draw the text 1729 * @param isRtl whether the run is in RTL direction 1730 * @param paint the paint 1731 */ 1732 public void drawTextRun(@NonNull char[] text, int index, int count, int contextIndex, 1733 int contextCount, float x, float y, boolean isRtl, @NonNull Paint paint) { 1734 1735 if (text == null) { 1736 throw new NullPointerException("text is null"); 1737 } 1738 if (paint == null) { 1739 throw new NullPointerException("paint is null"); 1740 } 1741 if ((index | count | contextIndex | contextCount | index - contextIndex 1742 | (contextIndex + contextCount) - (index + count) 1743 | text.length - (contextIndex + contextCount)) < 0) { 1744 throw new IndexOutOfBoundsException(); 1745 } 1746 1747 native_drawTextRun(mNativeCanvasWrapper, text, index, count, contextIndex, contextCount, 1748 x, y, isRtl, paint.getNativeInstance(), paint.mNativeTypeface); 1749 } 1750 1751 /** 1752 * Draw a run of text, all in a single direction, with optional context for complex text 1753 * shaping. 1754 * 1755 * <p>The run of text includes the characters from {@code start} to {@code end} in the text. In 1756 * addition, the range {@code contextStart} to {@code contextEnd} is used as context for the 1757 * purpose of complex text shaping, such as Arabic text potentially shaped differently based on 1758 * the text next to it. 1759 * 1760 * <p>All text outside the range {@code contextStart..contextEnd} is ignored. The text between 1761 * {@code start} and {@code end} will be laid out and drawn. 1762 * 1763 * <p>The direction of the run is explicitly specified by {@code isRtl}. Thus, this method is 1764 * suitable only for runs of a single direction. Alignment of the text is as determined by the 1765 * Paint's TextAlign value. Further, {@code 0 <= contextStart <= start <= end <= contextEnd 1766 * <= text.length} must hold on entry. 1767 * 1768 * <p>Also see {@link android.graphics.Paint#getRunAdvance} for a corresponding method to 1769 * measure the text; the advance width of the text drawn matches the value obtained from that 1770 * method. 1771 * 1772 * @param text the text to render 1773 * @param start the start of the text to render. Data before this position 1774 * can be used for shaping context. 1775 * @param end the end of the text to render. Data at or after this 1776 * position can be used for shaping context. 1777 * @param contextStart the index of the start of the shaping context 1778 * @param contextEnd the index of the end of the shaping context 1779 * @param x the x position at which to draw the text 1780 * @param y the y position at which to draw the text 1781 * @param isRtl whether the run is in RTL direction 1782 * @param paint the paint 1783 * 1784 * @see #drawTextRun(char[], int, int, int, int, float, float, boolean, Paint) 1785 */ 1786 public void drawTextRun(@NonNull CharSequence text, int start, int end, int contextStart, 1787 int contextEnd, float x, float y, boolean isRtl, @NonNull Paint paint) { 1788 1789 if (text == null) { 1790 throw new NullPointerException("text is null"); 1791 } 1792 if (paint == null) { 1793 throw new NullPointerException("paint is null"); 1794 } 1795 if ((start | end | contextStart | contextEnd | start - contextStart | end - start 1796 | contextEnd - end | text.length() - contextEnd) < 0) { 1797 throw new IndexOutOfBoundsException(); 1798 } 1799 1800 if (text instanceof String || text instanceof SpannedString || 1801 text instanceof SpannableString) { 1802 native_drawTextRun(mNativeCanvasWrapper, text.toString(), start, end, contextStart, 1803 contextEnd, x, y, isRtl, paint.getNativeInstance(), paint.mNativeTypeface); 1804 } else if (text instanceof GraphicsOperations) { 1805 ((GraphicsOperations) text).drawTextRun(this, start, end, 1806 contextStart, contextEnd, x, y, isRtl, paint); 1807 } else { 1808 int contextLen = contextEnd - contextStart; 1809 int len = end - start; 1810 char[] buf = TemporaryBuffer.obtain(contextLen); 1811 TextUtils.getChars(text, contextStart, contextEnd, buf, 0); 1812 native_drawTextRun(mNativeCanvasWrapper, buf, start - contextStart, len, 1813 0, contextLen, x, y, isRtl, paint.getNativeInstance(), paint.mNativeTypeface); 1814 TemporaryBuffer.recycle(buf); 1815 } 1816 } 1817 1818 /** 1819 * Draw the text in the array, with each character's origin specified by 1820 * the pos array. 1821 * 1822 * This method does not support glyph composition and decomposition and 1823 * should therefore not be used to render complex scripts. It also doesn't 1824 * handle supplementary characters (eg emoji). 1825 * 1826 * @param text The text to be drawn 1827 * @param index The index of the first character to draw 1828 * @param count The number of characters to draw, starting from index. 1829 * @param pos Array of [x,y] positions, used to position each 1830 * character 1831 * @param paint The paint used for the text (e.g. color, size, style) 1832 */ 1833 @Deprecated 1834 public void drawPosText(@NonNull char[] text, int index, int count, 1835 @NonNull @Size(multiple=2) float[] pos, 1836 @NonNull Paint paint) { 1837 if (index < 0 || index + count > text.length || count*2 > pos.length) { 1838 throw new IndexOutOfBoundsException(); 1839 } 1840 for (int i = 0; i < count; i++) { 1841 drawText(text, index + i, 1, pos[i * 2], pos[i * 2 + 1], paint); 1842 } 1843 } 1844 1845 /** 1846 * Draw the text in the array, with each character's origin specified by 1847 * the pos array. 1848 * 1849 * This method does not support glyph composition and decomposition and 1850 * should therefore not be used to render complex scripts. It also doesn't 1851 * handle supplementary characters (eg emoji). 1852 * 1853 * @param text The text to be drawn 1854 * @param pos Array of [x,y] positions, used to position each character 1855 * @param paint The paint used for the text (e.g. color, size, style) 1856 */ 1857 @Deprecated 1858 public void drawPosText(@NonNull String text, @NonNull @Size(multiple=2) float[] pos, 1859 @NonNull Paint paint) { 1860 drawPosText(text.toCharArray(), 0, text.length(), pos, paint); 1861 } 1862 1863 /** 1864 * Draw the text, with origin at (x,y), using the specified paint, along 1865 * the specified path. The paint's Align setting determins where along the 1866 * path to start the text. 1867 * 1868 * @param text The text to be drawn 1869 * @param path The path the text should follow for its baseline 1870 * @param hOffset The distance along the path to add to the text's 1871 * starting position 1872 * @param vOffset The distance above(-) or below(+) the path to position 1873 * the text 1874 * @param paint The paint used for the text (e.g. color, size, style) 1875 */ 1876 public void drawTextOnPath(@NonNull char[] text, int index, int count, @NonNull Path path, 1877 float hOffset, float vOffset, @NonNull Paint paint) { 1878 if (index < 0 || index + count > text.length) { 1879 throw new ArrayIndexOutOfBoundsException(); 1880 } 1881 native_drawTextOnPath(mNativeCanvasWrapper, text, index, count, 1882 path.ni(), hOffset, vOffset, 1883 paint.mBidiFlags, paint.getNativeInstance(), paint.mNativeTypeface); 1884 } 1885 1886 /** 1887 * Draw the text, with origin at (x,y), using the specified paint, along 1888 * the specified path. The paint's Align setting determins where along the 1889 * path to start the text. 1890 * 1891 * @param text The text to be drawn 1892 * @param path The path the text should follow for its baseline 1893 * @param hOffset The distance along the path to add to the text's 1894 * starting position 1895 * @param vOffset The distance above(-) or below(+) the path to position 1896 * the text 1897 * @param paint The paint used for the text (e.g. color, size, style) 1898 */ 1899 public void drawTextOnPath(@NonNull String text, @NonNull Path path, float hOffset, 1900 float vOffset, @NonNull Paint paint) { 1901 if (text.length() > 0) { 1902 native_drawTextOnPath(mNativeCanvasWrapper, text, path.ni(), hOffset, vOffset, 1903 paint.mBidiFlags, paint.getNativeInstance(), paint.mNativeTypeface); 1904 } 1905 } 1906 1907 /** 1908 * Save the canvas state, draw the picture, and restore the canvas state. 1909 * This differs from picture.draw(canvas), which does not perform any 1910 * save/restore. 1911 * 1912 * <p> 1913 * <strong>Note:</strong> This forces the picture to internally call 1914 * {@link Picture#endRecording} in order to prepare for playback. 1915 * 1916 * @param picture The picture to be drawn 1917 */ 1918 public void drawPicture(@NonNull Picture picture) { 1919 picture.endRecording(); 1920 int restoreCount = save(); 1921 picture.draw(this); 1922 restoreToCount(restoreCount); 1923 } 1924 1925 /** 1926 * Draw the picture, stretched to fit into the dst rectangle. 1927 */ 1928 public void drawPicture(@NonNull Picture picture, @NonNull RectF dst) { 1929 save(); 1930 translate(dst.left, dst.top); 1931 if (picture.getWidth() > 0 && picture.getHeight() > 0) { 1932 scale(dst.width() / picture.getWidth(), dst.height() / picture.getHeight()); 1933 } 1934 drawPicture(picture); 1935 restore(); 1936 } 1937 1938 /** 1939 * Draw the picture, stretched to fit into the dst rectangle. 1940 */ 1941 public void drawPicture(@NonNull Picture picture, @NonNull Rect dst) { 1942 save(); 1943 translate(dst.left, dst.top); 1944 if (picture.getWidth() > 0 && picture.getHeight() > 0) { 1945 scale((float) dst.width() / picture.getWidth(), 1946 (float) dst.height() / picture.getHeight()); 1947 } 1948 drawPicture(picture); 1949 restore(); 1950 } 1951 1952 /** 1953 * Releases the resources associated with this canvas. 1954 * 1955 * @hide 1956 */ 1957 public void release() { 1958 mFinalizer.dispose(); 1959 } 1960 1961 /** 1962 * Free up as much memory as possible from private caches (e.g. fonts, images) 1963 * 1964 * @hide 1965 */ 1966 public static native void freeCaches(); 1967 1968 /** 1969 * Free up text layout caches 1970 * 1971 * @hide 1972 */ 1973 public static native void freeTextLayoutCaches(); 1974 1975 private static native long initRaster(Bitmap bitmap); 1976 private static native void native_setBitmap(long canvasHandle, 1977 Bitmap bitmap); 1978 private static native boolean native_isOpaque(long canvasHandle); 1979 private static native void native_setHighContrastText(long renderer, boolean highContrastText); 1980 private static native int native_getWidth(long canvasHandle); 1981 private static native int native_getHeight(long canvasHandle); 1982 1983 private static native int native_save(long canvasHandle, int saveFlags); 1984 private static native int native_saveLayer(long nativeCanvas, float l, 1985 float t, float r, float b, 1986 long nativePaint, 1987 int layerFlags); 1988 private static native int native_saveLayerAlpha(long nativeCanvas, float l, 1989 float t, float r, float b, 1990 int alpha, int layerFlags); 1991 private static native void native_restore(long canvasHandle, boolean tolerateUnderflow); 1992 private static native void native_restoreToCount(long canvasHandle, 1993 int saveCount, 1994 boolean tolerateUnderflow); 1995 private static native int native_getSaveCount(long canvasHandle); 1996 1997 private static native void native_translate(long canvasHandle, 1998 float dx, float dy); 1999 private static native void native_scale(long canvasHandle, 2000 float sx, float sy); 2001 private static native void native_rotate(long canvasHandle, float degrees); 2002 private static native void native_skew(long canvasHandle, 2003 float sx, float sy); 2004 private static native void native_concat(long nativeCanvas, 2005 long nativeMatrix); 2006 private static native void native_setMatrix(long nativeCanvas, 2007 long nativeMatrix); 2008 private static native boolean native_clipRect(long nativeCanvas, 2009 float left, float top, 2010 float right, float bottom, 2011 int regionOp); 2012 private static native boolean native_clipPath(long nativeCanvas, 2013 long nativePath, 2014 int regionOp); 2015 private static native boolean native_clipRegion(long nativeCanvas, 2016 long nativeRegion, 2017 int regionOp); 2018 private static native void nativeSetDrawFilter(long nativeCanvas, 2019 long nativeFilter); 2020 private static native boolean native_getClipBounds(long nativeCanvas, 2021 Rect bounds); 2022 private static native void native_getCTM(long nativeCanvas, 2023 long nativeMatrix); 2024 private static native boolean native_quickReject(long nativeCanvas, 2025 long nativePath); 2026 private static native boolean native_quickReject(long nativeCanvas, 2027 float left, float top, 2028 float right, float bottom); 2029 private static native void native_drawColor(long nativeCanvas, int color, 2030 int mode); 2031 private static native void native_drawPaint(long nativeCanvas, 2032 long nativePaint); 2033 private static native void native_drawPoint(long canvasHandle, float x, float y, 2034 long paintHandle); 2035 private static native void native_drawPoints(long canvasHandle, float[] pts, 2036 int offset, int count, 2037 long paintHandle); 2038 private static native void native_drawLine(long nativeCanvas, float startX, 2039 float startY, float stopX, 2040 float stopY, long nativePaint); 2041 private static native void native_drawLines(long canvasHandle, float[] pts, 2042 int offset, int count, 2043 long paintHandle); 2044 private static native void native_drawRect(long nativeCanvas, float left, 2045 float top, float right, 2046 float bottom, 2047 long nativePaint); 2048 private static native void native_drawOval(long nativeCanvas, float left, float top, 2049 float right, float bottom, long nativePaint); 2050 private static native void native_drawCircle(long nativeCanvas, float cx, 2051 float cy, float radius, 2052 long nativePaint); 2053 private static native void native_drawArc(long nativeCanvas, float left, float top, 2054 float right, float bottom, 2055 float startAngle, float sweep, boolean useCenter, 2056 long nativePaint); 2057 private static native void native_drawRoundRect(long nativeCanvas, 2058 float left, float top, float right, float bottom, 2059 float rx, float ry, long nativePaint); 2060 private static native void native_drawPath(long nativeCanvas, 2061 long nativePath, 2062 long nativePaint); 2063 private static native void native_drawRegion(long nativeCanvas, 2064 long nativeRegion, long nativePaint); 2065 private native void native_drawBitmap(long nativeCanvas, Bitmap bitmap, 2066 float left, float top, 2067 long nativePaintOrZero, 2068 int canvasDensity, 2069 int screenDensity, 2070 int bitmapDensity); 2071 private native void native_drawBitmap(long nativeCanvas, Bitmap bitmap, 2072 float srcLeft, float srcTop, float srcRight, float srcBottom, 2073 float dstLeft, float dstTop, float dstRight, float dstBottom, 2074 long nativePaintOrZero, int screenDensity, int bitmapDensity); 2075 private static native void native_drawBitmap(long nativeCanvas, int[] colors, 2076 int offset, int stride, float x, 2077 float y, int width, int height, 2078 boolean hasAlpha, 2079 long nativePaintOrZero); 2080 private static native void nativeDrawBitmapMatrix(long nativeCanvas, 2081 Bitmap bitmap, 2082 long nativeMatrix, 2083 long nativePaint); 2084 private static native void nativeDrawBitmapMesh(long nativeCanvas, 2085 Bitmap bitmap, 2086 int meshWidth, int meshHeight, 2087 float[] verts, int vertOffset, 2088 int[] colors, int colorOffset, 2089 long nativePaint); 2090 private static native void nativeDrawVertices(long nativeCanvas, int mode, int n, 2091 float[] verts, int vertOffset, float[] texs, int texOffset, 2092 int[] colors, int colorOffset, short[] indices, 2093 int indexOffset, int indexCount, long nativePaint); 2094 2095 private static native void native_drawText(long nativeCanvas, char[] text, 2096 int index, int count, float x, 2097 float y, int flags, long nativePaint, 2098 long nativeTypeface); 2099 private static native void native_drawText(long nativeCanvas, String text, 2100 int start, int end, float x, 2101 float y, int flags, long nativePaint, 2102 long nativeTypeface); 2103 2104 private static native void native_drawTextRun(long nativeCanvas, String text, 2105 int start, int end, int contextStart, int contextEnd, 2106 float x, float y, boolean isRtl, long nativePaint, long nativeTypeface); 2107 2108 private static native void native_drawTextRun(long nativeCanvas, char[] text, 2109 int start, int count, int contextStart, int contextCount, 2110 float x, float y, boolean isRtl, long nativePaint, long nativeTypeface); 2111 2112 private static native void native_drawTextOnPath(long nativeCanvas, 2113 char[] text, int index, 2114 int count, long nativePath, 2115 float hOffset, 2116 float vOffset, int bidiFlags, 2117 long nativePaint, long nativeTypeface); 2118 private static native void native_drawTextOnPath(long nativeCanvas, 2119 String text, long nativePath, 2120 float hOffset, 2121 float vOffset, 2122 int flags, long nativePaint, long nativeTypeface); 2123 private static native void finalizer(long nativeCanvas); 2124} 2125