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