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