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