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