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