Paint.java revision 536afe6ef79a663e59c3b9781c561f7029ee9319
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.graphics; 18 19import android.annotation.ColorInt; 20import android.annotation.NonNull; 21import android.annotation.Size; 22import android.text.GraphicsOperations; 23import android.text.SpannableString; 24import android.text.SpannedString; 25import android.text.TextUtils; 26import android.util.LocaleList; 27 28import java.util.Locale; 29 30/** 31 * The Paint class holds the style and color information about how to draw 32 * geometries, text and bitmaps. 33 */ 34public class Paint { 35 36 private long mNativePaint; 37 private long mNativeShader = 0; 38 39 /** 40 * @hide 41 */ 42 public long mNativeTypeface; 43 44 private ColorFilter mColorFilter; 45 private MaskFilter mMaskFilter; 46 private PathEffect mPathEffect; 47 private Rasterizer mRasterizer; 48 private Shader mShader; 49 private Typeface mTypeface; 50 private Xfermode mXfermode; 51 52 private boolean mHasCompatScaling; 53 private float mCompatScaling; 54 private float mInvCompatScaling; 55 56 private LocaleList mLocales; 57 private String mFontFeatureSettings; 58 59 /** 60 * @hide 61 */ 62 public int mBidiFlags = BIDI_DEFAULT_LTR; 63 64 static final Style[] sStyleArray = { 65 Style.FILL, Style.STROKE, Style.FILL_AND_STROKE 66 }; 67 static final Cap[] sCapArray = { 68 Cap.BUTT, Cap.ROUND, Cap.SQUARE 69 }; 70 static final Join[] sJoinArray = { 71 Join.MITER, Join.ROUND, Join.BEVEL 72 }; 73 static final Align[] sAlignArray = { 74 Align.LEFT, Align.CENTER, Align.RIGHT 75 }; 76 77 /** 78 * Paint flag that enables antialiasing when drawing. 79 * 80 * <p>Enabling this flag will cause all draw operations that support 81 * antialiasing to use it.</p> 82 * 83 * @see #Paint(int) 84 * @see #setFlags(int) 85 */ 86 public static final int ANTI_ALIAS_FLAG = 0x01; 87 /** 88 * Paint flag that enables bilinear sampling on scaled bitmaps. 89 * 90 * <p>If cleared, scaled bitmaps will be drawn with nearest neighbor 91 * sampling, likely resulting in artifacts. This should generally be on 92 * when drawing bitmaps, unless performance-bound (rendering to software 93 * canvas) or preferring pixelation artifacts to blurriness when scaling 94 * significantly.</p> 95 * 96 * <p>If bitmaps are scaled for device density at creation time (as 97 * resource bitmaps often are) the filtering will already have been 98 * done.</p> 99 * 100 * @see #Paint(int) 101 * @see #setFlags(int) 102 */ 103 public static final int FILTER_BITMAP_FLAG = 0x02; 104 /** 105 * Paint flag that enables dithering when blitting. 106 * 107 * <p>Enabling this flag applies a dither to any blit operation where the 108 * target's colour space is more constrained than the source. 109 * 110 * @see #Paint(int) 111 * @see #setFlags(int) 112 */ 113 public static final int DITHER_FLAG = 0x04; 114 /** 115 * Paint flag that applies an underline decoration to drawn text. 116 * 117 * @see #Paint(int) 118 * @see #setFlags(int) 119 */ 120 public static final int UNDERLINE_TEXT_FLAG = 0x08; 121 /** 122 * Paint flag that applies a strike-through decoration to drawn text. 123 * 124 * @see #Paint(int) 125 * @see #setFlags(int) 126 */ 127 public static final int STRIKE_THRU_TEXT_FLAG = 0x10; 128 /** 129 * Paint flag that applies a synthetic bolding effect to drawn text. 130 * 131 * <p>Enabling this flag will cause text draw operations to apply a 132 * simulated bold effect when drawing a {@link Typeface} that is not 133 * already bold.</p> 134 * 135 * @see #Paint(int) 136 * @see #setFlags(int) 137 */ 138 public static final int FAKE_BOLD_TEXT_FLAG = 0x20; 139 /** 140 * Paint flag that enables smooth linear scaling of text. 141 * 142 * <p>Enabling this flag does not actually scale text, but rather adjusts 143 * text draw operations to deal gracefully with smooth adjustment of scale. 144 * When this flag is enabled, font hinting is disabled to prevent shape 145 * deformation between scale factors, and glyph caching is disabled due to 146 * the large number of glyph images that will be generated.</p> 147 * 148 * <p>{@link #SUBPIXEL_TEXT_FLAG} should be used in conjunction with this 149 * flag to prevent glyph positions from snapping to whole pixel values as 150 * scale factor is adjusted.</p> 151 * 152 * @see #Paint(int) 153 * @see #setFlags(int) 154 */ 155 public static final int LINEAR_TEXT_FLAG = 0x40; 156 /** 157 * Paint flag that enables subpixel positioning of text. 158 * 159 * <p>Enabling this flag causes glyph advances to be computed with subpixel 160 * accuracy.</p> 161 * 162 * <p>This can be used with {@link #LINEAR_TEXT_FLAG} to prevent text from 163 * jittering during smooth scale transitions.</p> 164 * 165 * @see #Paint(int) 166 * @see #setFlags(int) 167 */ 168 public static final int SUBPIXEL_TEXT_FLAG = 0x80; 169 /** Legacy Paint flag, no longer used. */ 170 public static final int DEV_KERN_TEXT_FLAG = 0x100; 171 /** @hide bit mask for the flag enabling subpixel glyph rendering for text */ 172 public static final int LCD_RENDER_TEXT_FLAG = 0x200; 173 /** 174 * Paint flag that enables the use of bitmap fonts when drawing text. 175 * 176 * <p>Disabling this flag will prevent text draw operations from using 177 * embedded bitmap strikes in fonts, causing fonts with both scalable 178 * outlines and bitmap strikes to draw only the scalable outlines, and 179 * fonts with only bitmap strikes to not draw at all.</p> 180 * 181 * @see #Paint(int) 182 * @see #setFlags(int) 183 */ 184 public static final int EMBEDDED_BITMAP_TEXT_FLAG = 0x400; 185 /** @hide bit mask for the flag forcing freetype's autohinter on for text */ 186 public static final int AUTO_HINTING_TEXT_FLAG = 0x800; 187 /** @hide bit mask for the flag enabling vertical rendering for text */ 188 public static final int VERTICAL_TEXT_FLAG = 0x1000; 189 190 // These flags are always set on a new/reset paint, even if flags 0 is passed. 191 static final int HIDDEN_DEFAULT_PAINT_FLAGS = DEV_KERN_TEXT_FLAG | EMBEDDED_BITMAP_TEXT_FLAG; 192 193 /** 194 * Font hinter option that disables font hinting. 195 * 196 * @see #setHinting(int) 197 */ 198 public static final int HINTING_OFF = 0x0; 199 200 /** 201 * Font hinter option that enables font hinting. 202 * 203 * @see #setHinting(int) 204 */ 205 public static final int HINTING_ON = 0x1; 206 207 /** 208 * Bidi flag to set LTR paragraph direction. 209 * 210 * @hide 211 */ 212 public static final int BIDI_LTR = 0x0; 213 214 /** 215 * Bidi flag to set RTL paragraph direction. 216 * 217 * @hide 218 */ 219 public static final int BIDI_RTL = 0x1; 220 221 /** 222 * Bidi flag to detect paragraph direction via heuristics, defaulting to 223 * LTR. 224 * 225 * @hide 226 */ 227 public static final int BIDI_DEFAULT_LTR = 0x2; 228 229 /** 230 * Bidi flag to detect paragraph direction via heuristics, defaulting to 231 * RTL. 232 * 233 * @hide 234 */ 235 public static final int BIDI_DEFAULT_RTL = 0x3; 236 237 /** 238 * Bidi flag to override direction to all LTR (ignore bidi). 239 * 240 * @hide 241 */ 242 public static final int BIDI_FORCE_LTR = 0x4; 243 244 /** 245 * Bidi flag to override direction to all RTL (ignore bidi). 246 * 247 * @hide 248 */ 249 public static final int BIDI_FORCE_RTL = 0x5; 250 251 /** 252 * Maximum Bidi flag value. 253 * @hide 254 */ 255 private static final int BIDI_MAX_FLAG_VALUE = BIDI_FORCE_RTL; 256 257 /** 258 * Mask for bidi flags. 259 * @hide 260 */ 261 private static final int BIDI_FLAG_MASK = 0x7; 262 263 /** 264 * Flag for getTextRunAdvances indicating left-to-right run direction. 265 * @hide 266 */ 267 public static final int DIRECTION_LTR = 0; 268 269 /** 270 * Flag for getTextRunAdvances indicating right-to-left run direction. 271 * @hide 272 */ 273 public static final int DIRECTION_RTL = 1; 274 275 /** 276 * Option for getTextRunCursor to compute the valid cursor after 277 * offset or the limit of the context, whichever is less. 278 * @hide 279 */ 280 public static final int CURSOR_AFTER = 0; 281 282 /** 283 * Option for getTextRunCursor to compute the valid cursor at or after 284 * the offset or the limit of the context, whichever is less. 285 * @hide 286 */ 287 public static final int CURSOR_AT_OR_AFTER = 1; 288 289 /** 290 * Option for getTextRunCursor to compute the valid cursor before 291 * offset or the start of the context, whichever is greater. 292 * @hide 293 */ 294 public static final int CURSOR_BEFORE = 2; 295 296 /** 297 * Option for getTextRunCursor to compute the valid cursor at or before 298 * offset or the start of the context, whichever is greater. 299 * @hide 300 */ 301 public static final int CURSOR_AT_OR_BEFORE = 3; 302 303 /** 304 * Option for getTextRunCursor to return offset if the cursor at offset 305 * is valid, or -1 if it isn't. 306 * @hide 307 */ 308 public static final int CURSOR_AT = 4; 309 310 /** 311 * Maximum cursor option value. 312 */ 313 private static final int CURSOR_OPT_MAX_VALUE = CURSOR_AT; 314 315 /** 316 * The Style specifies if the primitive being drawn is filled, stroked, or 317 * both (in the same color). The default is FILL. 318 */ 319 public enum Style { 320 /** 321 * Geometry and text drawn with this style will be filled, ignoring all 322 * stroke-related settings in the paint. 323 */ 324 FILL (0), 325 /** 326 * Geometry and text drawn with this style will be stroked, respecting 327 * the stroke-related fields on the paint. 328 */ 329 STROKE (1), 330 /** 331 * Geometry and text drawn with this style will be both filled and 332 * stroked at the same time, respecting the stroke-related fields on 333 * the paint. This mode can give unexpected results if the geometry 334 * is oriented counter-clockwise. This restriction does not apply to 335 * either FILL or STROKE. 336 */ 337 FILL_AND_STROKE (2); 338 339 Style(int nativeInt) { 340 this.nativeInt = nativeInt; 341 } 342 final int nativeInt; 343 } 344 345 /** 346 * The Cap specifies the treatment for the beginning and ending of 347 * stroked lines and paths. The default is BUTT. 348 */ 349 public enum Cap { 350 /** 351 * The stroke ends with the path, and does not project beyond it. 352 */ 353 BUTT (0), 354 /** 355 * The stroke projects out as a semicircle, with the center at the 356 * end of the path. 357 */ 358 ROUND (1), 359 /** 360 * The stroke projects out as a square, with the center at the end 361 * of the path. 362 */ 363 SQUARE (2); 364 365 private Cap(int nativeInt) { 366 this.nativeInt = nativeInt; 367 } 368 final int nativeInt; 369 } 370 371 /** 372 * The Join specifies the treatment where lines and curve segments 373 * join on a stroked path. The default is MITER. 374 */ 375 public enum Join { 376 /** 377 * The outer edges of a join meet at a sharp angle 378 */ 379 MITER (0), 380 /** 381 * The outer edges of a join meet in a circular arc. 382 */ 383 ROUND (1), 384 /** 385 * The outer edges of a join meet with a straight line 386 */ 387 BEVEL (2); 388 389 private Join(int nativeInt) { 390 this.nativeInt = nativeInt; 391 } 392 final int nativeInt; 393 } 394 395 /** 396 * Align specifies how drawText aligns its text relative to the 397 * [x,y] coordinates. The default is LEFT. 398 */ 399 public enum Align { 400 /** 401 * The text is drawn to the right of the x,y origin 402 */ 403 LEFT (0), 404 /** 405 * The text is drawn centered horizontally on the x,y origin 406 */ 407 CENTER (1), 408 /** 409 * The text is drawn to the left of the x,y origin 410 */ 411 RIGHT (2); 412 413 private Align(int nativeInt) { 414 this.nativeInt = nativeInt; 415 } 416 final int nativeInt; 417 } 418 419 /** 420 * Create a new paint with default settings. 421 */ 422 public Paint() { 423 this(0); 424 } 425 426 /** 427 * Create a new paint with the specified flags. Use setFlags() to change 428 * these after the paint is created. 429 * 430 * @param flags initial flag bits, as if they were passed via setFlags(). 431 */ 432 public Paint(int flags) { 433 mNativePaint = native_init(); 434 setFlags(flags | HIDDEN_DEFAULT_PAINT_FLAGS); 435 // TODO: Turning off hinting has undesirable side effects, we need to 436 // revisit hinting once we add support for subpixel positioning 437 // setHinting(DisplayMetrics.DENSITY_DEVICE >= DisplayMetrics.DENSITY_TV 438 // ? HINTING_OFF : HINTING_ON); 439 mCompatScaling = mInvCompatScaling = 1; 440 setTextLocales(LocaleList.getDefault()); 441 } 442 443 /** 444 * Create a new paint, initialized with the attributes in the specified 445 * paint parameter. 446 * 447 * @param paint Existing paint used to initialized the attributes of the 448 * new paint. 449 */ 450 public Paint(Paint paint) { 451 mNativePaint = native_initWithPaint(paint.getNativeInstance()); 452 setClassVariablesFrom(paint); 453 } 454 455 /** Restores the paint to its default settings. */ 456 public void reset() { 457 native_reset(mNativePaint); 458 setFlags(HIDDEN_DEFAULT_PAINT_FLAGS); 459 460 // TODO: Turning off hinting has undesirable side effects, we need to 461 // revisit hinting once we add support for subpixel positioning 462 // setHinting(DisplayMetrics.DENSITY_DEVICE >= DisplayMetrics.DENSITY_TV 463 // ? HINTING_OFF : HINTING_ON); 464 465 mColorFilter = null; 466 mMaskFilter = null; 467 mPathEffect = null; 468 mRasterizer = null; 469 mShader = null; 470 mNativeShader = 0; 471 mTypeface = null; 472 mNativeTypeface = 0; 473 mXfermode = null; 474 475 mHasCompatScaling = false; 476 mCompatScaling = 1; 477 mInvCompatScaling = 1; 478 479 mBidiFlags = BIDI_DEFAULT_LTR; 480 setTextLocales(LocaleList.getDefault()); 481 setElegantTextHeight(false); 482 mFontFeatureSettings = null; 483 } 484 485 /** 486 * Copy the fields from src into this paint. This is equivalent to calling 487 * get() on all of the src fields, and calling the corresponding set() 488 * methods on this. 489 */ 490 public void set(Paint src) { 491 if (this != src) { 492 // copy over the native settings 493 native_set(mNativePaint, src.mNativePaint); 494 setClassVariablesFrom(src); 495 } 496 } 497 498 /** 499 * Set all class variables using current values from the given 500 * {@link Paint}. 501 */ 502 private void setClassVariablesFrom(Paint paint) { 503 mColorFilter = paint.mColorFilter; 504 mMaskFilter = paint.mMaskFilter; 505 mPathEffect = paint.mPathEffect; 506 mRasterizer = paint.mRasterizer; 507 mShader = paint.mShader; 508 mNativeShader = paint.mNativeShader; 509 mTypeface = paint.mTypeface; 510 mNativeTypeface = paint.mNativeTypeface; 511 mXfermode = paint.mXfermode; 512 513 mHasCompatScaling = paint.mHasCompatScaling; 514 mCompatScaling = paint.mCompatScaling; 515 mInvCompatScaling = paint.mInvCompatScaling; 516 517 mBidiFlags = paint.mBidiFlags; 518 mLocales = paint.mLocales; 519 mFontFeatureSettings = paint.mFontFeatureSettings; 520 } 521 522 /** @hide */ 523 public void setCompatibilityScaling(float factor) { 524 if (factor == 1.0) { 525 mHasCompatScaling = false; 526 mCompatScaling = mInvCompatScaling = 1.0f; 527 } else { 528 mHasCompatScaling = true; 529 mCompatScaling = factor; 530 mInvCompatScaling = 1.0f/factor; 531 } 532 } 533 534 /** 535 * Return the pointer to the native object while ensuring that any 536 * mutable objects that are attached to the paint are also up-to-date. 537 * 538 * @hide 539 */ 540 public long getNativeInstance() { 541 long newNativeShader = mShader == null ? 0 : mShader.getNativeInstance(); 542 if (newNativeShader != mNativeShader) { 543 mNativeShader = newNativeShader; 544 native_setShader(mNativePaint, mNativeShader); 545 } 546 return mNativePaint; 547 } 548 549 /** 550 * Return the bidi flags on the paint. 551 * 552 * @return the bidi flags on the paint 553 * @hide 554 */ 555 public int getBidiFlags() { 556 return mBidiFlags; 557 } 558 559 /** 560 * Set the bidi flags on the paint. 561 * @hide 562 */ 563 public void setBidiFlags(int flags) { 564 // only flag value is the 3-bit BIDI control setting 565 flags &= BIDI_FLAG_MASK; 566 if (flags > BIDI_MAX_FLAG_VALUE) { 567 throw new IllegalArgumentException("unknown bidi flag: " + flags); 568 } 569 mBidiFlags = flags; 570 } 571 572 /** 573 * Return the paint's flags. Use the Flag enum to test flag values. 574 * 575 * @return the paint's flags (see enums ending in _Flag for bit masks) 576 */ 577 public native int getFlags(); 578 579 /** 580 * Set the paint's flags. Use the Flag enum to specific flag values. 581 * 582 * @param flags The new flag bits for the paint 583 */ 584 public native void setFlags(int flags); 585 586 /** 587 * Return the paint's hinting mode. Returns either 588 * {@link #HINTING_OFF} or {@link #HINTING_ON}. 589 */ 590 public native int getHinting(); 591 592 /** 593 * Set the paint's hinting mode. May be either 594 * {@link #HINTING_OFF} or {@link #HINTING_ON}. 595 */ 596 public native void setHinting(int mode); 597 598 /** 599 * Helper for getFlags(), returning true if ANTI_ALIAS_FLAG bit is set 600 * AntiAliasing smooths out the edges of what is being drawn, but is has 601 * no impact on the interior of the shape. See setDither() and 602 * setFilterBitmap() to affect how colors are treated. 603 * 604 * @return true if the antialias bit is set in the paint's flags. 605 */ 606 public final boolean isAntiAlias() { 607 return (getFlags() & ANTI_ALIAS_FLAG) != 0; 608 } 609 610 /** 611 * Helper for setFlags(), setting or clearing the ANTI_ALIAS_FLAG bit 612 * AntiAliasing smooths out the edges of what is being drawn, but is has 613 * no impact on the interior of the shape. See setDither() and 614 * setFilterBitmap() to affect how colors are treated. 615 * 616 * @param aa true to set the antialias bit in the flags, false to clear it 617 */ 618 public native void setAntiAlias(boolean aa); 619 620 /** 621 * Helper for getFlags(), returning true if DITHER_FLAG bit is set 622 * Dithering affects how colors that are higher precision than the device 623 * are down-sampled. No dithering is generally faster, but higher precision 624 * colors are just truncated down (e.g. 8888 -> 565). Dithering tries to 625 * distribute the error inherent in this process, to reduce the visual 626 * artifacts. 627 * 628 * @return true if the dithering bit is set in the paint's flags. 629 */ 630 public final boolean isDither() { 631 return (getFlags() & DITHER_FLAG) != 0; 632 } 633 634 /** 635 * Helper for setFlags(), setting or clearing the DITHER_FLAG bit 636 * Dithering affects how colors that are higher precision than the device 637 * are down-sampled. No dithering is generally faster, but higher precision 638 * colors are just truncated down (e.g. 8888 -> 565). Dithering tries to 639 * distribute the error inherent in this process, to reduce the visual 640 * artifacts. 641 * 642 * @param dither true to set the dithering bit in flags, false to clear it 643 */ 644 public native void setDither(boolean dither); 645 646 /** 647 * Helper for getFlags(), returning true if LINEAR_TEXT_FLAG bit is set 648 * 649 * @return true if the lineartext bit is set in the paint's flags 650 */ 651 public final boolean isLinearText() { 652 return (getFlags() & LINEAR_TEXT_FLAG) != 0; 653 } 654 655 /** 656 * Helper for setFlags(), setting or clearing the LINEAR_TEXT_FLAG bit 657 * 658 * @param linearText true to set the linearText bit in the paint's flags, 659 * false to clear it. 660 */ 661 public native void setLinearText(boolean linearText); 662 663 /** 664 * Helper for getFlags(), returning true if SUBPIXEL_TEXT_FLAG bit is set 665 * 666 * @return true if the subpixel bit is set in the paint's flags 667 */ 668 public final boolean isSubpixelText() { 669 return (getFlags() & SUBPIXEL_TEXT_FLAG) != 0; 670 } 671 672 /** 673 * Helper for setFlags(), setting or clearing the SUBPIXEL_TEXT_FLAG bit 674 * 675 * @param subpixelText true to set the subpixelText bit in the paint's 676 * flags, false to clear it. 677 */ 678 public native void setSubpixelText(boolean subpixelText); 679 680 /** 681 * Helper for getFlags(), returning true if UNDERLINE_TEXT_FLAG bit is set 682 * 683 * @return true if the underlineText bit is set in the paint's flags. 684 */ 685 public final boolean isUnderlineText() { 686 return (getFlags() & UNDERLINE_TEXT_FLAG) != 0; 687 } 688 689 /** 690 * Helper for setFlags(), setting or clearing the UNDERLINE_TEXT_FLAG bit 691 * 692 * @param underlineText true to set the underlineText bit in the paint's 693 * flags, false to clear it. 694 */ 695 public native void setUnderlineText(boolean underlineText); 696 697 /** 698 * Helper for getFlags(), returning true if STRIKE_THRU_TEXT_FLAG bit is set 699 * 700 * @return true if the strikeThruText bit is set in the paint's flags. 701 */ 702 public final boolean isStrikeThruText() { 703 return (getFlags() & STRIKE_THRU_TEXT_FLAG) != 0; 704 } 705 706 /** 707 * Helper for setFlags(), setting or clearing the STRIKE_THRU_TEXT_FLAG bit 708 * 709 * @param strikeThruText true to set the strikeThruText bit in the paint's 710 * flags, false to clear it. 711 */ 712 public native void setStrikeThruText(boolean strikeThruText); 713 714 /** 715 * Helper for getFlags(), returning true if FAKE_BOLD_TEXT_FLAG bit is set 716 * 717 * @return true if the fakeBoldText bit is set in the paint's flags. 718 */ 719 public final boolean isFakeBoldText() { 720 return (getFlags() & FAKE_BOLD_TEXT_FLAG) != 0; 721 } 722 723 /** 724 * Helper for setFlags(), setting or clearing the FAKE_BOLD_TEXT_FLAG bit 725 * 726 * @param fakeBoldText true to set the fakeBoldText bit in the paint's 727 * flags, false to clear it. 728 */ 729 public native void setFakeBoldText(boolean fakeBoldText); 730 731 /** 732 * Whether or not the bitmap filter is activated. 733 * Filtering affects the sampling of bitmaps when they are transformed. 734 * Filtering does not affect how the colors in the bitmap are converted into 735 * device pixels. That is dependent on dithering and xfermodes. 736 * 737 * @see #setFilterBitmap(boolean) setFilterBitmap() 738 */ 739 public final boolean isFilterBitmap() { 740 return (getFlags() & FILTER_BITMAP_FLAG) != 0; 741 } 742 743 /** 744 * Helper for setFlags(), setting or clearing the FILTER_BITMAP_FLAG bit. 745 * Filtering affects the sampling of bitmaps when they are transformed. 746 * Filtering does not affect how the colors in the bitmap are converted into 747 * device pixels. That is dependent on dithering and xfermodes. 748 * 749 * @param filter true to set the FILTER_BITMAP_FLAG bit in the paint's 750 * flags, false to clear it. 751 */ 752 public native void setFilterBitmap(boolean filter); 753 754 /** 755 * Return the paint's style, used for controlling how primitives' 756 * geometries are interpreted (except for drawBitmap, which always assumes 757 * FILL_STYLE). 758 * 759 * @return the paint's style setting (Fill, Stroke, StrokeAndFill) 760 */ 761 public Style getStyle() { 762 return sStyleArray[native_getStyle(mNativePaint)]; 763 } 764 765 /** 766 * Set the paint's style, used for controlling how primitives' 767 * geometries are interpreted (except for drawBitmap, which always assumes 768 * Fill). 769 * 770 * @param style The new style to set in the paint 771 */ 772 public void setStyle(Style style) { 773 native_setStyle(mNativePaint, style.nativeInt); 774 } 775 776 /** 777 * Return the paint's color. Note that the color is a 32bit value 778 * containing alpha as well as r,g,b. This 32bit value is not premultiplied, 779 * meaning that its alpha can be any value, regardless of the values of 780 * r,g,b. See the Color class for more details. 781 * 782 * @return the paint's color (and alpha). 783 */ 784 @ColorInt 785 public native int getColor(); 786 787 /** 788 * Set the paint's color. Note that the color is an int containing alpha 789 * as well as r,g,b. This 32bit value is not premultiplied, meaning that 790 * its alpha can be any value, regardless of the values of r,g,b. 791 * See the Color class for more details. 792 * 793 * @param color The new color (including alpha) to set in the paint. 794 */ 795 public native void setColor(@ColorInt int color); 796 797 /** 798 * Helper to getColor() that just returns the color's alpha value. This is 799 * the same as calling getColor() >>> 24. It always returns a value between 800 * 0 (completely transparent) and 255 (completely opaque). 801 * 802 * @return the alpha component of the paint's color. 803 */ 804 public native int getAlpha(); 805 806 /** 807 * Helper to setColor(), that only assigns the color's alpha value, 808 * leaving its r,g,b values unchanged. Results are undefined if the alpha 809 * value is outside of the range [0..255] 810 * 811 * @param a set the alpha component [0..255] of the paint's color. 812 */ 813 public native void setAlpha(int a); 814 815 /** 816 * Helper to setColor(), that takes a,r,g,b and constructs the color int 817 * 818 * @param a The new alpha component (0..255) of the paint's color. 819 * @param r The new red component (0..255) of the paint's color. 820 * @param g The new green component (0..255) of the paint's color. 821 * @param b The new blue component (0..255) of the paint's color. 822 */ 823 public void setARGB(int a, int r, int g, int b) { 824 setColor((a << 24) | (r << 16) | (g << 8) | b); 825 } 826 827 /** 828 * Return the width for stroking. 829 * <p /> 830 * A value of 0 strokes in hairline mode. 831 * Hairlines always draws a single pixel independent of the canva's matrix. 832 * 833 * @return the paint's stroke width, used whenever the paint's style is 834 * Stroke or StrokeAndFill. 835 */ 836 public native float getStrokeWidth(); 837 838 /** 839 * Set the width for stroking. 840 * Pass 0 to stroke in hairline mode. 841 * Hairlines always draws a single pixel independent of the canva's matrix. 842 * 843 * @param width set the paint's stroke width, used whenever the paint's 844 * style is Stroke or StrokeAndFill. 845 */ 846 public native void setStrokeWidth(float width); 847 848 /** 849 * Return the paint's stroke miter value. Used to control the behavior 850 * of miter joins when the joins angle is sharp. 851 * 852 * @return the paint's miter limit, used whenever the paint's style is 853 * Stroke or StrokeAndFill. 854 */ 855 public native float getStrokeMiter(); 856 857 /** 858 * Set the paint's stroke miter value. This is used to control the behavior 859 * of miter joins when the joins angle is sharp. This value must be >= 0. 860 * 861 * @param miter set the miter limit on the paint, used whenever the paint's 862 * style is Stroke or StrokeAndFill. 863 */ 864 public native void setStrokeMiter(float miter); 865 866 /** 867 * Return the paint's Cap, controlling how the start and end of stroked 868 * lines and paths are treated. 869 * 870 * @return the line cap style for the paint, used whenever the paint's 871 * style is Stroke or StrokeAndFill. 872 */ 873 public Cap getStrokeCap() { 874 return sCapArray[native_getStrokeCap(mNativePaint)]; 875 } 876 877 /** 878 * Set the paint's Cap. 879 * 880 * @param cap set the paint's line cap style, used whenever the paint's 881 * style is Stroke or StrokeAndFill. 882 */ 883 public void setStrokeCap(Cap cap) { 884 native_setStrokeCap(mNativePaint, cap.nativeInt); 885 } 886 887 /** 888 * Return the paint's stroke join type. 889 * 890 * @return the paint's Join. 891 */ 892 public Join getStrokeJoin() { 893 return sJoinArray[native_getStrokeJoin(mNativePaint)]; 894 } 895 896 /** 897 * Set the paint's Join. 898 * 899 * @param join set the paint's Join, used whenever the paint's style is 900 * Stroke or StrokeAndFill. 901 */ 902 public void setStrokeJoin(Join join) { 903 native_setStrokeJoin(mNativePaint, join.nativeInt); 904 } 905 906 /** 907 * Applies any/all effects (patheffect, stroking) to src, returning the 908 * result in dst. The result is that drawing src with this paint will be 909 * the same as drawing dst with a default paint (at least from the 910 * geometric perspective). 911 * 912 * @param src input path 913 * @param dst output path (may be the same as src) 914 * @return true if the path should be filled, or false if it should be 915 * drawn with a hairline (width == 0) 916 */ 917 public boolean getFillPath(Path src, Path dst) { 918 return native_getFillPath(mNativePaint, src.ni(), dst.ni()); 919 } 920 921 /** 922 * Get the paint's shader object. 923 * 924 * @return the paint's shader (or null) 925 */ 926 public Shader getShader() { 927 return mShader; 928 } 929 930 /** 931 * Set or clear the shader object. 932 * <p /> 933 * Pass null to clear any previous shader. 934 * As a convenience, the parameter passed is also returned. 935 * 936 * @param shader May be null. the new shader to be installed in the paint 937 * @return shader 938 */ 939 public Shader setShader(Shader shader) { 940 // Defer setting the shader natively until getNativeInstance() is called 941 mShader = shader; 942 return shader; 943 } 944 945 /** 946 * Get the paint's colorfilter (maybe be null). 947 * 948 * @return the paint's colorfilter (maybe be null) 949 */ 950 public ColorFilter getColorFilter() { 951 return mColorFilter; 952 } 953 954 /** 955 * Set or clear the paint's colorfilter, returning the parameter. 956 * 957 * @param filter May be null. The new filter to be installed in the paint 958 * @return filter 959 */ 960 public ColorFilter setColorFilter(ColorFilter filter) { 961 long filterNative = 0; 962 if (filter != null) 963 filterNative = filter.native_instance; 964 native_setColorFilter(mNativePaint, filterNative); 965 mColorFilter = filter; 966 return filter; 967 } 968 969 /** 970 * Get the paint's xfermode object. 971 * 972 * @return the paint's xfermode (or null) 973 */ 974 public Xfermode getXfermode() { 975 return mXfermode; 976 } 977 978 /** 979 * Set or clear the xfermode object. 980 * <p /> 981 * Pass null to clear any previous xfermode. 982 * As a convenience, the parameter passed is also returned. 983 * 984 * @param xfermode May be null. The xfermode to be installed in the paint 985 * @return xfermode 986 */ 987 public Xfermode setXfermode(Xfermode xfermode) { 988 long xfermodeNative = 0; 989 if (xfermode != null) 990 xfermodeNative = xfermode.native_instance; 991 native_setXfermode(mNativePaint, xfermodeNative); 992 mXfermode = xfermode; 993 return xfermode; 994 } 995 996 /** 997 * Get the paint's patheffect object. 998 * 999 * @return the paint's patheffect (or null) 1000 */ 1001 public PathEffect getPathEffect() { 1002 return mPathEffect; 1003 } 1004 1005 /** 1006 * Set or clear the patheffect object. 1007 * <p /> 1008 * Pass null to clear any previous patheffect. 1009 * As a convenience, the parameter passed is also returned. 1010 * 1011 * @param effect May be null. The patheffect to be installed in the paint 1012 * @return effect 1013 */ 1014 public PathEffect setPathEffect(PathEffect effect) { 1015 long effectNative = 0; 1016 if (effect != null) { 1017 effectNative = effect.native_instance; 1018 } 1019 native_setPathEffect(mNativePaint, effectNative); 1020 mPathEffect = effect; 1021 return effect; 1022 } 1023 1024 /** 1025 * Get the paint's maskfilter object. 1026 * 1027 * @return the paint's maskfilter (or null) 1028 */ 1029 public MaskFilter getMaskFilter() { 1030 return mMaskFilter; 1031 } 1032 1033 /** 1034 * Set or clear the maskfilter object. 1035 * <p /> 1036 * Pass null to clear any previous maskfilter. 1037 * As a convenience, the parameter passed is also returned. 1038 * 1039 * @param maskfilter May be null. The maskfilter to be installed in the 1040 * paint 1041 * @return maskfilter 1042 */ 1043 public MaskFilter setMaskFilter(MaskFilter maskfilter) { 1044 long maskfilterNative = 0; 1045 if (maskfilter != null) { 1046 maskfilterNative = maskfilter.native_instance; 1047 } 1048 native_setMaskFilter(mNativePaint, maskfilterNative); 1049 mMaskFilter = maskfilter; 1050 return maskfilter; 1051 } 1052 1053 /** 1054 * Get the paint's typeface object. 1055 * <p /> 1056 * The typeface object identifies which font to use when drawing or 1057 * measuring text. 1058 * 1059 * @return the paint's typeface (or null) 1060 */ 1061 public Typeface getTypeface() { 1062 return mTypeface; 1063 } 1064 1065 /** 1066 * Set or clear the typeface object. 1067 * <p /> 1068 * Pass null to clear any previous typeface. 1069 * As a convenience, the parameter passed is also returned. 1070 * 1071 * @param typeface May be null. The typeface to be installed in the paint 1072 * @return typeface 1073 */ 1074 public Typeface setTypeface(Typeface typeface) { 1075 long typefaceNative = 0; 1076 if (typeface != null) { 1077 typefaceNative = typeface.native_instance; 1078 } 1079 native_setTypeface(mNativePaint, typefaceNative); 1080 mTypeface = typeface; 1081 mNativeTypeface = typefaceNative; 1082 return typeface; 1083 } 1084 1085 /** 1086 * Get the paint's rasterizer (or null). 1087 * <p /> 1088 * The raster controls/modifies how paths/text are turned into alpha masks. 1089 * 1090 * @return the paint's rasterizer (or null) 1091 * 1092 * @deprecated Rasterizer is not supported by either the HW or PDF backends. 1093 */ 1094 @Deprecated 1095 public Rasterizer getRasterizer() { 1096 return mRasterizer; 1097 } 1098 1099 /** 1100 * Set or clear the rasterizer object. 1101 * <p /> 1102 * Pass null to clear any previous rasterizer. 1103 * As a convenience, the parameter passed is also returned. 1104 * 1105 * @param rasterizer May be null. The new rasterizer to be installed in 1106 * the paint. 1107 * @return rasterizer 1108 * 1109 * @deprecated Rasterizer is not supported by either the HW or PDF backends. 1110 */ 1111 @Deprecated 1112 public Rasterizer setRasterizer(Rasterizer rasterizer) { 1113 long rasterizerNative = 0; 1114 if (rasterizer != null) { 1115 rasterizerNative = rasterizer.native_instance; 1116 } 1117 native_setRasterizer(mNativePaint, rasterizerNative); 1118 mRasterizer = rasterizer; 1119 return rasterizer; 1120 } 1121 1122 /** 1123 * This draws a shadow layer below the main layer, with the specified 1124 * offset and color, and blur radius. If radius is 0, then the shadow 1125 * layer is removed. 1126 * <p> 1127 * Can be used to create a blurred shadow underneath text. Support for use 1128 * with other drawing operations is constrained to the software rendering 1129 * pipeline. 1130 * <p> 1131 * The alpha of the shadow will be the paint's alpha if the shadow color is 1132 * opaque, or the alpha from the shadow color if not. 1133 */ 1134 public void setShadowLayer(float radius, float dx, float dy, int shadowColor) { 1135 native_setShadowLayer(mNativePaint, radius, dx, dy, shadowColor); 1136 } 1137 1138 /** 1139 * Clear the shadow layer. 1140 */ 1141 public void clearShadowLayer() { 1142 setShadowLayer(0, 0, 0, 0); 1143 } 1144 1145 /** 1146 * Checks if the paint has a shadow layer attached 1147 * 1148 * @return true if the paint has a shadow layer attached and false otherwise 1149 * @hide 1150 */ 1151 public boolean hasShadowLayer() { 1152 return native_hasShadowLayer(mNativePaint); 1153 } 1154 1155 /** 1156 * Return the paint's Align value for drawing text. This controls how the 1157 * text is positioned relative to its origin. LEFT align means that all of 1158 * the text will be drawn to the right of its origin (i.e. the origin 1159 * specifieds the LEFT edge of the text) and so on. 1160 * 1161 * @return the paint's Align value for drawing text. 1162 */ 1163 public Align getTextAlign() { 1164 return sAlignArray[native_getTextAlign(mNativePaint)]; 1165 } 1166 1167 /** 1168 * Set the paint's text alignment. This controls how the 1169 * text is positioned relative to its origin. LEFT align means that all of 1170 * the text will be drawn to the right of its origin (i.e. the origin 1171 * specifieds the LEFT edge of the text) and so on. 1172 * 1173 * @param align set the paint's Align value for drawing text. 1174 */ 1175 public void setTextAlign(Align align) { 1176 native_setTextAlign(mNativePaint, align.nativeInt); 1177 } 1178 1179 /** 1180 * Get the text's primary Locale. Note that this is not all of the locale-related information 1181 * Paint has. Use {@link #getTextLocales()} to get the complete list. 1182 * 1183 * @return the paint's primary Locale used for drawing text, never null. 1184 */ 1185 @NonNull 1186 public Locale getTextLocale() { 1187 return mLocales.getPrimary(); 1188 } 1189 1190 /** 1191 * Get the text locale list. 1192 * 1193 * @return the paint's LocaleList used for drawing text, never null or empty. 1194 */ 1195 @NonNull @Size(min=1) 1196 public LocaleList getTextLocales() { 1197 return mLocales; 1198 } 1199 1200 /** 1201 * Set the text locale list to a one-member list consisting of just the locale. 1202 * 1203 * See {@link #setTextLocales(LocaleList)} for how the locale list affects 1204 * the way the text is drawn for some languages. 1205 * 1206 * @param locale the paint's locale value for drawing text, must not be null. 1207 */ 1208 public void setTextLocale(@NonNull Locale locale) { 1209 if (locale == null) { 1210 throw new IllegalArgumentException("locale cannot be null"); 1211 } 1212 if (mLocales != null && mLocales.size() == 1 && locale.equals(mLocales.getPrimary())) { 1213 return; 1214 } 1215 mLocales = new LocaleList(locale); 1216 native_setTextLocale(mNativePaint, locale.toString()); 1217 } 1218 1219 /** 1220 * Set the text locale list. 1221 * 1222 * The text locale list affects how the text is drawn for some languages. 1223 * 1224 * For example, if the locale list contains {@link Locale#CHINESE} or {@link Locale#CHINA}, 1225 * then the text renderer will prefer to draw text using a Chinese font. Likewise, 1226 * if the locale list contains {@link Locale#JAPANESE} or {@link Locale#JAPAN}, then the text 1227 * renderer will prefer to draw text using a Japanese font. If the locale list contains both, 1228 * the order those locales appear in the list is considered for deciding the font. 1229 * 1230 * This distinction is important because Chinese and Japanese text both use many 1231 * of the same Unicode code points but their appearance is subtly different for 1232 * each language. 1233 * 1234 * By default, the text locale list is initialized to a one-member list just containing the 1235 * system locale (as returned by {@link LocaleList#getDefault()}). This assumes that the text to 1236 * be rendered will most likely be in the user's preferred language. 1237 * 1238 * If the actual language or languages of the text is/are known, then they can be provided to 1239 * the text renderer using this method. The text renderer may attempt to guess the 1240 * language script based on the contents of the text to be drawn independent of 1241 * the text locale here. Specifying the text locales just helps it do a better 1242 * job in certain ambiguous cases. 1243 * 1244 * @param locales the paint's locale list for drawing text, must not be null or empty. 1245 */ 1246 public void setTextLocales(@NonNull @Size(min=1) LocaleList locales) { 1247 if (locales == null || locales.isEmpty()) { 1248 throw new IllegalArgumentException("locales cannot be null or empty"); 1249 } 1250 if (locales.equals(mLocales)) return; 1251 mLocales = locales; 1252 // TODO: Pass the whole LocaleList to native code 1253 native_setTextLocale(mNativePaint, locales.getPrimary().toString()); 1254 } 1255 1256 /** 1257 * Get the elegant metrics flag. 1258 * 1259 * @return true if elegant metrics are enabled for text drawing. 1260 */ 1261 public native boolean isElegantTextHeight(); 1262 1263 /** 1264 * Set the paint's elegant height metrics flag. This setting selects font 1265 * variants that have not been compacted to fit Latin-based vertical 1266 * metrics, and also increases top and bottom bounds to provide more space. 1267 * 1268 * @param elegant set the paint's elegant metrics flag for drawing text. 1269 */ 1270 public native void setElegantTextHeight(boolean elegant); 1271 1272 /** 1273 * Return the paint's text size. 1274 * 1275 * @return the paint's text size. 1276 */ 1277 public native float getTextSize(); 1278 1279 /** 1280 * Set the paint's text size. This value must be > 0 1281 * 1282 * @param textSize set the paint's text size. 1283 */ 1284 public native void setTextSize(float textSize); 1285 1286 /** 1287 * Return the paint's horizontal scale factor for text. The default value 1288 * is 1.0. 1289 * 1290 * @return the paint's scale factor in X for drawing/measuring text 1291 */ 1292 public native float getTextScaleX(); 1293 1294 /** 1295 * Set the paint's horizontal scale factor for text. The default value 1296 * is 1.0. Values > 1.0 will stretch the text wider. Values < 1.0 will 1297 * stretch the text narrower. 1298 * 1299 * @param scaleX set the paint's scale in X for drawing/measuring text. 1300 */ 1301 public native void setTextScaleX(float scaleX); 1302 1303 /** 1304 * Return the paint's horizontal skew factor for text. The default value 1305 * is 0. 1306 * 1307 * @return the paint's skew factor in X for drawing text. 1308 */ 1309 public native float getTextSkewX(); 1310 1311 /** 1312 * Set the paint's horizontal skew factor for text. The default value 1313 * is 0. For approximating oblique text, use values around -0.25. 1314 * 1315 * @param skewX set the paint's skew factor in X for drawing text. 1316 */ 1317 public native void setTextSkewX(float skewX); 1318 1319 /** 1320 * Return the paint's letter-spacing for text. The default value 1321 * is 0. 1322 * 1323 * @return the paint's letter-spacing for drawing text. 1324 */ 1325 public float getLetterSpacing() { 1326 return native_getLetterSpacing(mNativePaint); 1327 } 1328 1329 /** 1330 * Set the paint's letter-spacing for text. The default value 1331 * is 0. The value is in 'EM' units. Typical values for slight 1332 * expansion will be around 0.05. Negative values tighten text. 1333 * 1334 * @param letterSpacing set the paint's letter-spacing for drawing text. 1335 */ 1336 public void setLetterSpacing(float letterSpacing) { 1337 native_setLetterSpacing(mNativePaint, letterSpacing); 1338 } 1339 1340 /** 1341 * Get font feature settings. Default is null. 1342 * 1343 * @return the paint's currently set font feature settings. 1344 */ 1345 public String getFontFeatureSettings() { 1346 return mFontFeatureSettings; 1347 } 1348 1349 /** 1350 * Set font feature settings. 1351 * 1352 * The format is the same as the CSS font-feature-settings attribute: 1353 * http://dev.w3.org/csswg/css-fonts/#propdef-font-feature-settings 1354 * 1355 * @param settings the font feature settings string to use, may be null. 1356 */ 1357 public void setFontFeatureSettings(String settings) { 1358 if (settings != null && settings.equals("")) { 1359 settings = null; 1360 } 1361 if ((settings == null && mFontFeatureSettings == null) 1362 || (settings != null && settings.equals(mFontFeatureSettings))) { 1363 return; 1364 } 1365 mFontFeatureSettings = settings; 1366 native_setFontFeatureSettings(mNativePaint, settings); 1367 } 1368 1369 /** 1370 * Get the current value of hyphen edit. 1371 * 1372 * @return the current hyphen edit value 1373 * 1374 * @hide 1375 */ 1376 public int getHyphenEdit() { 1377 return native_getHyphenEdit(mNativePaint); 1378 } 1379 1380 /** 1381 * Set a hyphen edit on the paint (causes a hyphen to be added to text when 1382 * measured or drawn). 1383 * 1384 * @param hyphen 0 for no edit, 1 for adding a hyphen (other values in future) 1385 * 1386 * @hide 1387 */ 1388 public void setHyphenEdit(int hyphen) { 1389 native_setHyphenEdit(mNativePaint, hyphen); 1390 } 1391 1392 /** 1393 * Return the distance above (negative) the baseline (ascent) based on the 1394 * current typeface and text size. 1395 * 1396 * @return the distance above (negative) the baseline (ascent) based on the 1397 * current typeface and text size. 1398 */ 1399 public native float ascent(); 1400 1401 /** 1402 * Return the distance below (positive) the baseline (descent) based on the 1403 * current typeface and text size. 1404 * 1405 * @return the distance below (positive) the baseline (descent) based on 1406 * the current typeface and text size. 1407 */ 1408 public native float descent(); 1409 1410 /** 1411 * Class that describes the various metrics for a font at a given text size. 1412 * Remember, Y values increase going down, so those values will be positive, 1413 * and values that measure distances going up will be negative. This class 1414 * is returned by getFontMetrics(). 1415 */ 1416 public static class FontMetrics { 1417 /** 1418 * The maximum distance above the baseline for the tallest glyph in 1419 * the font at a given text size. 1420 */ 1421 public float top; 1422 /** 1423 * The recommended distance above the baseline for singled spaced text. 1424 */ 1425 public float ascent; 1426 /** 1427 * The recommended distance below the baseline for singled spaced text. 1428 */ 1429 public float descent; 1430 /** 1431 * The maximum distance below the baseline for the lowest glyph in 1432 * the font at a given text size. 1433 */ 1434 public float bottom; 1435 /** 1436 * The recommended additional space to add between lines of text. 1437 */ 1438 public float leading; 1439 } 1440 1441 /** 1442 * Return the font's recommended interline spacing, given the Paint's 1443 * settings for typeface, textSize, etc. If metrics is not null, return the 1444 * fontmetric values in it. 1445 * 1446 * @param metrics If this object is not null, its fields are filled with 1447 * the appropriate values given the paint's text attributes. 1448 * @return the font's recommended interline spacing. 1449 */ 1450 public native float getFontMetrics(FontMetrics metrics); 1451 1452 /** 1453 * Allocates a new FontMetrics object, and then calls getFontMetrics(fm) 1454 * with it, returning the object. 1455 */ 1456 public FontMetrics getFontMetrics() { 1457 FontMetrics fm = new FontMetrics(); 1458 getFontMetrics(fm); 1459 return fm; 1460 } 1461 1462 /** 1463 * Convenience method for callers that want to have FontMetrics values as 1464 * integers. 1465 */ 1466 public static class FontMetricsInt { 1467 public int top; 1468 public int ascent; 1469 public int descent; 1470 public int bottom; 1471 public int leading; 1472 1473 @Override public String toString() { 1474 return "FontMetricsInt: top=" + top + " ascent=" + ascent + 1475 " descent=" + descent + " bottom=" + bottom + 1476 " leading=" + leading; 1477 } 1478 } 1479 1480 /** 1481 * Return the font's interline spacing, given the Paint's settings for 1482 * typeface, textSize, etc. If metrics is not null, return the fontmetric 1483 * values in it. Note: all values have been converted to integers from 1484 * floats, in such a way has to make the answers useful for both spacing 1485 * and clipping. If you want more control over the rounding, call 1486 * getFontMetrics(). 1487 * 1488 * @return the font's interline spacing. 1489 */ 1490 public native int getFontMetricsInt(FontMetricsInt fmi); 1491 1492 public FontMetricsInt getFontMetricsInt() { 1493 FontMetricsInt fm = new FontMetricsInt(); 1494 getFontMetricsInt(fm); 1495 return fm; 1496 } 1497 1498 /** 1499 * Return the recommend line spacing based on the current typeface and 1500 * text size. 1501 * 1502 * @return recommend line spacing based on the current typeface and 1503 * text size. 1504 */ 1505 public float getFontSpacing() { 1506 return getFontMetrics(null); 1507 } 1508 1509 /** 1510 * Return the width of the text. 1511 * 1512 * @param text The text to measure. Cannot be null. 1513 * @param index The index of the first character to start measuring 1514 * @param count THe number of characters to measure, beginning with start 1515 * @return The width of the text 1516 */ 1517 public float measureText(char[] text, int index, int count) { 1518 if (text == null) { 1519 throw new IllegalArgumentException("text cannot be null"); 1520 } 1521 if ((index | count) < 0 || index + count > text.length) { 1522 throw new ArrayIndexOutOfBoundsException(); 1523 } 1524 1525 if (text.length == 0 || count == 0) { 1526 return 0f; 1527 } 1528 if (!mHasCompatScaling) { 1529 return (float) Math.ceil(native_getTextAdvances(mNativePaint, mNativeTypeface, text, 1530 index, count, index, count, mBidiFlags, null, 0)); 1531 } 1532 1533 final float oldSize = getTextSize(); 1534 setTextSize(oldSize * mCompatScaling); 1535 float w = native_getTextAdvances(mNativePaint, mNativeTypeface, text, index, count, index, 1536 count, mBidiFlags, null, 0); 1537 setTextSize(oldSize); 1538 return (float) Math.ceil(w*mInvCompatScaling); 1539 } 1540 1541 /** 1542 * Return the width of the text. 1543 * 1544 * @param text The text to measure. Cannot be null. 1545 * @param start The index of the first character to start measuring 1546 * @param end 1 beyond the index of the last character to measure 1547 * @return The width of the text 1548 */ 1549 public float measureText(String text, int start, int end) { 1550 if (text == null) { 1551 throw new IllegalArgumentException("text cannot be null"); 1552 } 1553 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1554 throw new IndexOutOfBoundsException(); 1555 } 1556 1557 if (text.length() == 0 || start == end) { 1558 return 0f; 1559 } 1560 if (!mHasCompatScaling) { 1561 return (float) Math.ceil(native_getTextAdvances(mNativePaint, mNativeTypeface, text, 1562 start, end, start, end, mBidiFlags, null, 0)); 1563 } 1564 final float oldSize = getTextSize(); 1565 setTextSize(oldSize * mCompatScaling); 1566 float w = native_getTextAdvances(mNativePaint, mNativeTypeface, text, start, end, start, 1567 end, mBidiFlags, null, 0); 1568 setTextSize(oldSize); 1569 return (float) Math.ceil(w * mInvCompatScaling); 1570 } 1571 1572 /** 1573 * Return the width of the text. 1574 * 1575 * @param text The text to measure. Cannot be null. 1576 * @return The width of the text 1577 */ 1578 public float measureText(String text) { 1579 if (text == null) { 1580 throw new IllegalArgumentException("text cannot be null"); 1581 } 1582 return measureText(text, 0, text.length()); 1583 } 1584 1585 /** 1586 * Return the width of the text. 1587 * 1588 * @param text The text to measure 1589 * @param start The index of the first character to start measuring 1590 * @param end 1 beyond the index of the last character to measure 1591 * @return The width of the text 1592 */ 1593 public float measureText(CharSequence text, int start, int end) { 1594 if (text == null) { 1595 throw new IllegalArgumentException("text cannot be null"); 1596 } 1597 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1598 throw new IndexOutOfBoundsException(); 1599 } 1600 1601 if (text.length() == 0 || start == end) { 1602 return 0f; 1603 } 1604 if (text instanceof String) { 1605 return measureText((String)text, start, end); 1606 } 1607 if (text instanceof SpannedString || 1608 text instanceof SpannableString) { 1609 return measureText(text.toString(), start, end); 1610 } 1611 if (text instanceof GraphicsOperations) { 1612 return ((GraphicsOperations)text).measureText(start, end, this); 1613 } 1614 1615 char[] buf = TemporaryBuffer.obtain(end - start); 1616 TextUtils.getChars(text, start, end, buf, 0); 1617 float result = measureText(buf, 0, end - start); 1618 TemporaryBuffer.recycle(buf); 1619 return result; 1620 } 1621 1622 /** 1623 * Measure the text, stopping early if the measured width exceeds maxWidth. 1624 * Return the number of chars that were measured, and if measuredWidth is 1625 * not null, return in it the actual width measured. 1626 * 1627 * @param text The text to measure. Cannot be null. 1628 * @param index The offset into text to begin measuring at 1629 * @param count The number of maximum number of entries to measure. If count 1630 * is negative, then the characters are measured in reverse order. 1631 * @param maxWidth The maximum width to accumulate. 1632 * @param measuredWidth Optional. If not null, returns the actual width 1633 * measured. 1634 * @return The number of chars that were measured. Will always be <= 1635 * abs(count). 1636 */ 1637 public int breakText(char[] text, int index, int count, 1638 float maxWidth, float[] measuredWidth) { 1639 if (text == null) { 1640 throw new IllegalArgumentException("text cannot be null"); 1641 } 1642 if (index < 0 || text.length - index < Math.abs(count)) { 1643 throw new ArrayIndexOutOfBoundsException(); 1644 } 1645 1646 if (text.length == 0 || count == 0) { 1647 return 0; 1648 } 1649 if (!mHasCompatScaling) { 1650 return native_breakText(mNativePaint, mNativeTypeface, text, index, count, maxWidth, 1651 mBidiFlags, measuredWidth); 1652 } 1653 1654 final float oldSize = getTextSize(); 1655 setTextSize(oldSize * mCompatScaling); 1656 int res = native_breakText(mNativePaint, mNativeTypeface, text, index, count, 1657 maxWidth * mCompatScaling, mBidiFlags, measuredWidth); 1658 setTextSize(oldSize); 1659 if (measuredWidth != null) measuredWidth[0] *= mInvCompatScaling; 1660 return res; 1661 } 1662 1663 private static native int native_breakText(long native_object, long native_typeface, 1664 char[] text, int index, int count, 1665 float maxWidth, int bidiFlags, float[] measuredWidth); 1666 1667 /** 1668 * Measure the text, stopping early if the measured width exceeds maxWidth. 1669 * Return the number of chars that were measured, and if measuredWidth is 1670 * not null, return in it the actual width measured. 1671 * 1672 * @param text The text to measure. Cannot be null. 1673 * @param start The offset into text to begin measuring at 1674 * @param end The end of the text slice to measure. 1675 * @param measureForwards If true, measure forwards, starting at start. 1676 * Otherwise, measure backwards, starting with end. 1677 * @param maxWidth The maximum width to accumulate. 1678 * @param measuredWidth Optional. If not null, returns the actual width 1679 * measured. 1680 * @return The number of chars that were measured. Will always be <= 1681 * abs(end - start). 1682 */ 1683 public int breakText(CharSequence text, int start, int end, 1684 boolean measureForwards, 1685 float maxWidth, float[] measuredWidth) { 1686 if (text == null) { 1687 throw new IllegalArgumentException("text cannot be null"); 1688 } 1689 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1690 throw new IndexOutOfBoundsException(); 1691 } 1692 1693 if (text.length() == 0 || start == end) { 1694 return 0; 1695 } 1696 if (start == 0 && text instanceof String && end == text.length()) { 1697 return breakText((String) text, measureForwards, maxWidth, 1698 measuredWidth); 1699 } 1700 1701 char[] buf = TemporaryBuffer.obtain(end - start); 1702 int result; 1703 1704 TextUtils.getChars(text, start, end, buf, 0); 1705 1706 if (measureForwards) { 1707 result = breakText(buf, 0, end - start, maxWidth, measuredWidth); 1708 } else { 1709 result = breakText(buf, 0, -(end - start), maxWidth, measuredWidth); 1710 } 1711 1712 TemporaryBuffer.recycle(buf); 1713 return result; 1714 } 1715 1716 /** 1717 * Measure the text, stopping early if the measured width exceeds maxWidth. 1718 * Return the number of chars that were measured, and if measuredWidth is 1719 * not null, return in it the actual width measured. 1720 * 1721 * @param text The text to measure. Cannot be null. 1722 * @param measureForwards If true, measure forwards, starting with the 1723 * first character in the string. Otherwise, 1724 * measure backwards, starting with the 1725 * last character in the string. 1726 * @param maxWidth The maximum width to accumulate. 1727 * @param measuredWidth Optional. If not null, returns the actual width 1728 * measured. 1729 * @return The number of chars that were measured. Will always be <= 1730 * abs(count). 1731 */ 1732 public int breakText(String text, boolean measureForwards, 1733 float maxWidth, float[] measuredWidth) { 1734 if (text == null) { 1735 throw new IllegalArgumentException("text cannot be null"); 1736 } 1737 1738 if (text.length() == 0) { 1739 return 0; 1740 } 1741 if (!mHasCompatScaling) { 1742 return native_breakText(mNativePaint, mNativeTypeface, text, measureForwards, 1743 maxWidth, mBidiFlags, measuredWidth); 1744 } 1745 1746 final float oldSize = getTextSize(); 1747 setTextSize(oldSize*mCompatScaling); 1748 int res = native_breakText(mNativePaint, mNativeTypeface, text, measureForwards, 1749 maxWidth*mCompatScaling, mBidiFlags, measuredWidth); 1750 setTextSize(oldSize); 1751 if (measuredWidth != null) measuredWidth[0] *= mInvCompatScaling; 1752 return res; 1753 } 1754 1755 private static native int native_breakText(long native_object, long native_typeface, 1756 String text, boolean measureForwards, 1757 float maxWidth, int bidiFlags, float[] measuredWidth); 1758 1759 /** 1760 * Return the advance widths for the characters in the string. 1761 * 1762 * @param text The text to measure. Cannot be null. 1763 * @param index The index of the first char to to measure 1764 * @param count The number of chars starting with index to measure 1765 * @param widths array to receive the advance widths of the characters. 1766 * Must be at least a large as count. 1767 * @return the actual number of widths returned. 1768 */ 1769 public int getTextWidths(char[] text, int index, int count, 1770 float[] widths) { 1771 if (text == null) { 1772 throw new IllegalArgumentException("text cannot be null"); 1773 } 1774 if ((index | count) < 0 || index + count > text.length 1775 || count > widths.length) { 1776 throw new ArrayIndexOutOfBoundsException(); 1777 } 1778 1779 if (text.length == 0 || count == 0) { 1780 return 0; 1781 } 1782 if (!mHasCompatScaling) { 1783 native_getTextAdvances(mNativePaint, mNativeTypeface, text, index, count, index, count, 1784 mBidiFlags, widths, 0); 1785 return count; 1786 } 1787 1788 final float oldSize = getTextSize(); 1789 setTextSize(oldSize * mCompatScaling); 1790 native_getTextAdvances(mNativePaint, mNativeTypeface, text, index, count, index, count, 1791 mBidiFlags, widths, 0); 1792 setTextSize(oldSize); 1793 for (int i = 0; i < count; i++) { 1794 widths[i] *= mInvCompatScaling; 1795 } 1796 return count; 1797 } 1798 1799 /** 1800 * Return the advance widths for the characters in the string. 1801 * 1802 * @param text The text to measure. Cannot be null. 1803 * @param start The index of the first char to to measure 1804 * @param end The end of the text slice to measure 1805 * @param widths array to receive the advance widths of the characters. 1806 * Must be at least a large as (end - start). 1807 * @return the actual number of widths returned. 1808 */ 1809 public int getTextWidths(CharSequence text, int start, int end, 1810 float[] widths) { 1811 if (text == null) { 1812 throw new IllegalArgumentException("text cannot be null"); 1813 } 1814 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1815 throw new IndexOutOfBoundsException(); 1816 } 1817 if (end - start > widths.length) { 1818 throw new ArrayIndexOutOfBoundsException(); 1819 } 1820 1821 if (text.length() == 0 || start == end) { 1822 return 0; 1823 } 1824 if (text instanceof String) { 1825 return getTextWidths((String) text, start, end, widths); 1826 } 1827 if (text instanceof SpannedString || 1828 text instanceof SpannableString) { 1829 return getTextWidths(text.toString(), start, end, widths); 1830 } 1831 if (text instanceof GraphicsOperations) { 1832 return ((GraphicsOperations) text).getTextWidths(start, end, 1833 widths, this); 1834 } 1835 1836 char[] buf = TemporaryBuffer.obtain(end - start); 1837 TextUtils.getChars(text, start, end, buf, 0); 1838 int result = getTextWidths(buf, 0, end - start, widths); 1839 TemporaryBuffer.recycle(buf); 1840 return result; 1841 } 1842 1843 /** 1844 * Return the advance widths for the characters in the string. 1845 * 1846 * @param text The text to measure. Cannot be null. 1847 * @param start The index of the first char to to measure 1848 * @param end The end of the text slice to measure 1849 * @param widths array to receive the advance widths of the characters. 1850 * Must be at least a large as the text. 1851 * @return the number of code units in the specified text. 1852 */ 1853 public int getTextWidths(String text, int start, int end, float[] widths) { 1854 if (text == null) { 1855 throw new IllegalArgumentException("text cannot be null"); 1856 } 1857 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1858 throw new IndexOutOfBoundsException(); 1859 } 1860 if (end - start > widths.length) { 1861 throw new ArrayIndexOutOfBoundsException(); 1862 } 1863 1864 if (text.length() == 0 || start == end) { 1865 return 0; 1866 } 1867 if (!mHasCompatScaling) { 1868 native_getTextAdvances(mNativePaint, mNativeTypeface, text, start, end, start, end, 1869 mBidiFlags, widths, 0); 1870 return end - start; 1871 } 1872 1873 final float oldSize = getTextSize(); 1874 setTextSize(oldSize * mCompatScaling); 1875 native_getTextAdvances(mNativePaint, mNativeTypeface, text, start, end, start, end, 1876 mBidiFlags, widths, 0); 1877 setTextSize(oldSize); 1878 for (int i = 0; i < end - start; i++) { 1879 widths[i] *= mInvCompatScaling; 1880 } 1881 return end - start; 1882 } 1883 1884 /** 1885 * Return the advance widths for the characters in the string. 1886 * 1887 * @param text The text to measure 1888 * @param widths array to receive the advance widths of the characters. 1889 * Must be at least a large as the text. 1890 * @return the number of code units in the specified text. 1891 */ 1892 public int getTextWidths(String text, float[] widths) { 1893 return getTextWidths(text, 0, text.length(), widths); 1894 } 1895 1896 /** 1897 * Convenience overload that takes a char array instead of a 1898 * String. 1899 * 1900 * @see #getTextRunAdvances(String, int, int, int, int, boolean, float[], int) 1901 * @hide 1902 */ 1903 public float getTextRunAdvances(char[] chars, int index, int count, 1904 int contextIndex, int contextCount, boolean isRtl, float[] advances, 1905 int advancesIndex) { 1906 1907 if (chars == null) { 1908 throw new IllegalArgumentException("text cannot be null"); 1909 } 1910 if ((index | count | contextIndex | contextCount | advancesIndex 1911 | (index - contextIndex) | (contextCount - count) 1912 | ((contextIndex + contextCount) - (index + count)) 1913 | (chars.length - (contextIndex + contextCount)) 1914 | (advances == null ? 0 : 1915 (advances.length - (advancesIndex + count)))) < 0) { 1916 throw new IndexOutOfBoundsException(); 1917 } 1918 1919 if (chars.length == 0 || count == 0){ 1920 return 0f; 1921 } 1922 if (!mHasCompatScaling) { 1923 return native_getTextAdvances(mNativePaint, mNativeTypeface, chars, index, count, 1924 contextIndex, contextCount, isRtl ? BIDI_FORCE_RTL : BIDI_FORCE_LTR, advances, 1925 advancesIndex); 1926 } 1927 1928 final float oldSize = getTextSize(); 1929 setTextSize(oldSize * mCompatScaling); 1930 float res = native_getTextAdvances(mNativePaint, mNativeTypeface, chars, index, count, 1931 contextIndex, contextCount, isRtl ? BIDI_FORCE_RTL : BIDI_FORCE_LTR, advances, 1932 advancesIndex); 1933 setTextSize(oldSize); 1934 1935 if (advances != null) { 1936 for (int i = advancesIndex, e = i + count; i < e; i++) { 1937 advances[i] *= mInvCompatScaling; 1938 } 1939 } 1940 return res * mInvCompatScaling; // assume errors are not significant 1941 } 1942 1943 /** 1944 * Convenience overload that takes a CharSequence instead of a 1945 * String. 1946 * 1947 * @see #getTextRunAdvances(String, int, int, int, int, boolean, float[], int) 1948 * @hide 1949 */ 1950 public float getTextRunAdvances(CharSequence text, int start, int end, 1951 int contextStart, int contextEnd, boolean isRtl, float[] advances, 1952 int advancesIndex) { 1953 1954 if (text == null) { 1955 throw new IllegalArgumentException("text cannot be null"); 1956 } 1957 if ((start | end | contextStart | contextEnd | advancesIndex | (end - start) 1958 | (start - contextStart) | (contextEnd - end) 1959 | (text.length() - contextEnd) 1960 | (advances == null ? 0 : 1961 (advances.length - advancesIndex - (end - start)))) < 0) { 1962 throw new IndexOutOfBoundsException(); 1963 } 1964 1965 if (text instanceof String) { 1966 return getTextRunAdvances((String) text, start, end, 1967 contextStart, contextEnd, isRtl, advances, advancesIndex); 1968 } 1969 if (text instanceof SpannedString || 1970 text instanceof SpannableString) { 1971 return getTextRunAdvances(text.toString(), start, end, 1972 contextStart, contextEnd, isRtl, advances, advancesIndex); 1973 } 1974 if (text instanceof GraphicsOperations) { 1975 return ((GraphicsOperations) text).getTextRunAdvances(start, end, 1976 contextStart, contextEnd, isRtl, advances, advancesIndex, this); 1977 } 1978 if (text.length() == 0 || end == start) { 1979 return 0f; 1980 } 1981 1982 int contextLen = contextEnd - contextStart; 1983 int len = end - start; 1984 char[] buf = TemporaryBuffer.obtain(contextLen); 1985 TextUtils.getChars(text, contextStart, contextEnd, buf, 0); 1986 float result = getTextRunAdvances(buf, start - contextStart, len, 1987 0, contextLen, isRtl, advances, advancesIndex); 1988 TemporaryBuffer.recycle(buf); 1989 return result; 1990 } 1991 1992 /** 1993 * Returns the total advance width for the characters in the run 1994 * between start and end, and if advances is not null, the advance 1995 * assigned to each of these characters (java chars). 1996 * 1997 * <p>The trailing surrogate in a valid surrogate pair is assigned 1998 * an advance of 0. Thus the number of returned advances is 1999 * always equal to count, not to the number of unicode codepoints 2000 * represented by the run. 2001 * 2002 * <p>In the case of conjuncts or combining marks, the total 2003 * advance is assigned to the first logical character, and the 2004 * following characters are assigned an advance of 0. 2005 * 2006 * <p>This generates the sum of the advances of glyphs for 2007 * characters in a reordered cluster as the width of the first 2008 * logical character in the cluster, and 0 for the widths of all 2009 * other characters in the cluster. In effect, such clusters are 2010 * treated like conjuncts. 2011 * 2012 * <p>The shaping bounds limit the amount of context available 2013 * outside start and end that can be used for shaping analysis. 2014 * These bounds typically reflect changes in bidi level or font 2015 * metrics across which shaping does not occur. 2016 * 2017 * @param text the text to measure. Cannot be null. 2018 * @param start the index of the first character to measure 2019 * @param end the index past the last character to measure 2020 * @param contextStart the index of the first character to use for shaping context, 2021 * must be <= start 2022 * @param contextEnd the index past the last character to use for shaping context, 2023 * must be >= end 2024 * @param isRtl whether the run is in RTL direction 2025 * @param advances array to receive the advances, must have room for all advances, 2026 * can be null if only total advance is needed 2027 * @param advancesIndex the position in advances at which to put the 2028 * advance corresponding to the character at start 2029 * @return the total advance 2030 * 2031 * @hide 2032 */ 2033 public float getTextRunAdvances(String text, int start, int end, int contextStart, 2034 int contextEnd, boolean isRtl, float[] advances, int advancesIndex) { 2035 if (text == null) { 2036 throw new IllegalArgumentException("text cannot be null"); 2037 } 2038 if ((start | end | contextStart | contextEnd | advancesIndex | (end - start) 2039 | (start - contextStart) | (contextEnd - end) 2040 | (text.length() - contextEnd) 2041 | (advances == null ? 0 : 2042 (advances.length - advancesIndex - (end - start)))) < 0) { 2043 throw new IndexOutOfBoundsException(); 2044 } 2045 2046 if (text.length() == 0 || start == end) { 2047 return 0f; 2048 } 2049 2050 if (!mHasCompatScaling) { 2051 return native_getTextAdvances(mNativePaint, mNativeTypeface, text, start, end, 2052 contextStart, contextEnd, isRtl ? BIDI_FORCE_RTL : BIDI_FORCE_LTR, advances, 2053 advancesIndex); 2054 } 2055 2056 final float oldSize = getTextSize(); 2057 setTextSize(oldSize * mCompatScaling); 2058 float totalAdvance = native_getTextAdvances(mNativePaint, mNativeTypeface, text, start, 2059 end, contextStart, contextEnd, isRtl ? BIDI_FORCE_RTL : BIDI_FORCE_LTR, advances, 2060 advancesIndex); 2061 setTextSize(oldSize); 2062 2063 if (advances != null) { 2064 for (int i = advancesIndex, e = i + (end - start); i < e; i++) { 2065 advances[i] *= mInvCompatScaling; 2066 } 2067 } 2068 return totalAdvance * mInvCompatScaling; // assume errors are insignificant 2069 } 2070 2071 /** 2072 * Returns the next cursor position in the run. This avoids placing the 2073 * cursor between surrogates, between characters that form conjuncts, 2074 * between base characters and combining marks, or within a reordering 2075 * cluster. 2076 * 2077 * <p>ContextStart and offset are relative to the start of text. 2078 * The context is the shaping context for cursor movement, generally 2079 * the bounds of the metric span enclosing the cursor in the direction of 2080 * movement. 2081 * 2082 * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid 2083 * cursor position, this returns -1. Otherwise this will never return a 2084 * value before contextStart or after contextStart + contextLength. 2085 * 2086 * @param text the text 2087 * @param contextStart the start of the context 2088 * @param contextLength the length of the context 2089 * @param dir either {@link #DIRECTION_RTL} or {@link #DIRECTION_LTR} 2090 * @param offset the cursor position to move from 2091 * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER}, 2092 * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE}, 2093 * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT} 2094 * @return the offset of the next position, or -1 2095 * @hide 2096 */ 2097 public int getTextRunCursor(char[] text, int contextStart, int contextLength, 2098 int dir, int offset, int cursorOpt) { 2099 int contextEnd = contextStart + contextLength; 2100 if (((contextStart | contextEnd | offset | (contextEnd - contextStart) 2101 | (offset - contextStart) | (contextEnd - offset) 2102 | (text.length - contextEnd) | cursorOpt) < 0) 2103 || cursorOpt > CURSOR_OPT_MAX_VALUE) { 2104 throw new IndexOutOfBoundsException(); 2105 } 2106 2107 return native_getTextRunCursor(mNativePaint, text, 2108 contextStart, contextLength, dir, offset, cursorOpt); 2109 } 2110 2111 /** 2112 * Returns the next cursor position in the run. This avoids placing the 2113 * cursor between surrogates, between characters that form conjuncts, 2114 * between base characters and combining marks, or within a reordering 2115 * cluster. 2116 * 2117 * <p>ContextStart, contextEnd, and offset are relative to the start of 2118 * text. The context is the shaping context for cursor movement, generally 2119 * the bounds of the metric span enclosing the cursor in the direction of 2120 * movement. 2121 * 2122 * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid 2123 * cursor position, this returns -1. Otherwise this will never return a 2124 * value before contextStart or after contextEnd. 2125 * 2126 * @param text the text 2127 * @param contextStart the start of the context 2128 * @param contextEnd the end of the context 2129 * @param dir either {@link #DIRECTION_RTL} or {@link #DIRECTION_LTR} 2130 * @param offset the cursor position to move from 2131 * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER}, 2132 * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE}, 2133 * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT} 2134 * @return the offset of the next position, or -1 2135 * @hide 2136 */ 2137 public int getTextRunCursor(CharSequence text, int contextStart, 2138 int contextEnd, int dir, int offset, int cursorOpt) { 2139 2140 if (text instanceof String || text instanceof SpannedString || 2141 text instanceof SpannableString) { 2142 return getTextRunCursor(text.toString(), contextStart, contextEnd, 2143 dir, offset, cursorOpt); 2144 } 2145 if (text instanceof GraphicsOperations) { 2146 return ((GraphicsOperations) text).getTextRunCursor( 2147 contextStart, contextEnd, dir, offset, cursorOpt, this); 2148 } 2149 2150 int contextLen = contextEnd - contextStart; 2151 char[] buf = TemporaryBuffer.obtain(contextLen); 2152 TextUtils.getChars(text, contextStart, contextEnd, buf, 0); 2153 int relPos = getTextRunCursor(buf, 0, contextLen, dir, offset - contextStart, cursorOpt); 2154 TemporaryBuffer.recycle(buf); 2155 return (relPos == -1) ? -1 : relPos + contextStart; 2156 } 2157 2158 /** 2159 * Returns the next cursor position in the run. This avoids placing the 2160 * cursor between surrogates, between characters that form conjuncts, 2161 * between base characters and combining marks, or within a reordering 2162 * cluster. 2163 * 2164 * <p>ContextStart, contextEnd, and offset are relative to the start of 2165 * text. The context is the shaping context for cursor movement, generally 2166 * the bounds of the metric span enclosing the cursor in the direction of 2167 * movement. 2168 * 2169 * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid 2170 * cursor position, this returns -1. Otherwise this will never return a 2171 * value before contextStart or after contextEnd. 2172 * 2173 * @param text the text 2174 * @param contextStart the start of the context 2175 * @param contextEnd the end of the context 2176 * @param dir either {@link #DIRECTION_RTL} or {@link #DIRECTION_LTR} 2177 * @param offset the cursor position to move from 2178 * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER}, 2179 * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE}, 2180 * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT} 2181 * @return the offset of the next position, or -1 2182 * @hide 2183 */ 2184 public int getTextRunCursor(String text, int contextStart, int contextEnd, 2185 int dir, int offset, int cursorOpt) { 2186 if (((contextStart | contextEnd | offset | (contextEnd - contextStart) 2187 | (offset - contextStart) | (contextEnd - offset) 2188 | (text.length() - contextEnd) | cursorOpt) < 0) 2189 || cursorOpt > CURSOR_OPT_MAX_VALUE) { 2190 throw new IndexOutOfBoundsException(); 2191 } 2192 2193 return native_getTextRunCursor(mNativePaint, text, 2194 contextStart, contextEnd, dir, offset, cursorOpt); 2195 } 2196 2197 /** 2198 * Return the path (outline) for the specified text. 2199 * Note: just like Canvas.drawText, this will respect the Align setting in 2200 * the paint. 2201 * 2202 * @param text The text to retrieve the path from 2203 * @param index The index of the first character in text 2204 * @param count The number of characterss starting with index 2205 * @param x The x coordinate of the text's origin 2206 * @param y The y coordinate of the text's origin 2207 * @param path The path to receive the data describing the text. Must 2208 * be allocated by the caller. 2209 */ 2210 public void getTextPath(char[] text, int index, int count, 2211 float x, float y, Path path) { 2212 if ((index | count) < 0 || index + count > text.length) { 2213 throw new ArrayIndexOutOfBoundsException(); 2214 } 2215 native_getTextPath(mNativePaint, mNativeTypeface, mBidiFlags, text, index, count, x, y, 2216 path.ni()); 2217 } 2218 2219 /** 2220 * Return the path (outline) for the specified text. 2221 * Note: just like Canvas.drawText, this will respect the Align setting 2222 * in the paint. 2223 * 2224 * @param text The text to retrieve the path from 2225 * @param start The first character in the text 2226 * @param end 1 past the last charcter in the text 2227 * @param x The x coordinate of the text's origin 2228 * @param y The y coordinate of the text's origin 2229 * @param path The path to receive the data describing the text. Must 2230 * be allocated by the caller. 2231 */ 2232 public void getTextPath(String text, int start, int end, 2233 float x, float y, Path path) { 2234 if ((start | end | (end - start) | (text.length() - end)) < 0) { 2235 throw new IndexOutOfBoundsException(); 2236 } 2237 native_getTextPath(mNativePaint, mNativeTypeface, mBidiFlags, text, start, end, x, y, 2238 path.ni()); 2239 } 2240 2241 /** 2242 * Return in bounds (allocated by the caller) the smallest rectangle that 2243 * encloses all of the characters, with an implied origin at (0,0). 2244 * 2245 * @param text String to measure and return its bounds 2246 * @param start Index of the first char in the string to measure 2247 * @param end 1 past the last char in the string measure 2248 * @param bounds Returns the unioned bounds of all the text. Must be 2249 * allocated by the caller. 2250 */ 2251 public void getTextBounds(String text, int start, int end, Rect bounds) { 2252 if ((start | end | (end - start) | (text.length() - end)) < 0) { 2253 throw new IndexOutOfBoundsException(); 2254 } 2255 if (bounds == null) { 2256 throw new NullPointerException("need bounds Rect"); 2257 } 2258 nativeGetStringBounds(mNativePaint, mNativeTypeface, text, start, end, mBidiFlags, bounds); 2259 } 2260 2261 /** 2262 * Return in bounds (allocated by the caller) the smallest rectangle that 2263 * encloses all of the characters, with an implied origin at (0,0). 2264 * 2265 * @param text Array of chars to measure and return their unioned bounds 2266 * @param index Index of the first char in the array to measure 2267 * @param count The number of chars, beginning at index, to measure 2268 * @param bounds Returns the unioned bounds of all the text. Must be 2269 * allocated by the caller. 2270 */ 2271 public void getTextBounds(char[] text, int index, int count, Rect bounds) { 2272 if ((index | count) < 0 || index + count > text.length) { 2273 throw new ArrayIndexOutOfBoundsException(); 2274 } 2275 if (bounds == null) { 2276 throw new NullPointerException("need bounds Rect"); 2277 } 2278 nativeGetCharArrayBounds(mNativePaint, mNativeTypeface, text, index, count, mBidiFlags, 2279 bounds); 2280 } 2281 2282 /** 2283 * Determine whether the typeface set on the paint has a glyph supporting the string. The 2284 * simplest case is when the string contains a single character, in which this method 2285 * determines whether the font has the character. In the case of multiple characters, the 2286 * method returns true if there is a single glyph representing the ligature. For example, if 2287 * the input is a pair of regional indicator symbols, determine whether there is an emoji flag 2288 * for the pair. 2289 * 2290 * <p>Finally, if the string contains a variation selector, the method only returns true if 2291 * the fonts contains a glyph specific to that variation. 2292 * 2293 * <p>Checking is done on the entire fallback chain, not just the immediate font referenced. 2294 * 2295 * @param string the string to test whether there is glyph support 2296 * @return true if the typeface has a glyph for the string 2297 */ 2298 public boolean hasGlyph(String string) { 2299 return native_hasGlyph(mNativePaint, mNativeTypeface, mBidiFlags, string); 2300 } 2301 2302 /** 2303 * Measure cursor position within a run of text. 2304 * 2305 * <p>The run of text includes the characters from {@code start} to {@code end} in the text. In 2306 * addition, the range {@code contextStart} to {@code contextEnd} is used as context for the 2307 * purpose of complex text shaping, such as Arabic text potentially shaped differently based on 2308 * the text next to it. 2309 * 2310 * <p>All text outside the range {@code contextStart..contextEnd} is ignored. The text between 2311 * {@code start} and {@code end} will be laid out to be measured. 2312 * 2313 * <p>The returned width measurement is the advance from {@code start} to {@code offset}. It is 2314 * generally a positive value, no matter the direction of the run. If {@code offset == end}, 2315 * the return value is simply the width of the whole run from {@code start} to {@code end}. 2316 * 2317 * <p>Ligatures are formed for characters in the range {@code start..end} (but not for 2318 * {@code start..contextStart} or {@code end..contextEnd}). If {@code offset} points to a 2319 * character in the middle of such a formed ligature, but at a grapheme cluster boundary, the 2320 * return value will also reflect an advance in the middle of the ligature. See 2321 * {@link #getOffsetForAdvance} for more discussion of grapheme cluster boundaries. 2322 * 2323 * <p>The direction of the run is explicitly specified by {@code isRtl}. Thus, this method is 2324 * suitable only for runs of a single direction. 2325 * 2326 * <p>All indices are relative to the start of {@code text}. Further, {@code 0 <= contextStart 2327 * <= start <= offset <= end <= contextEnd <= text.length} must hold on entry. 2328 * 2329 * @param text the text to measure. Cannot be null. 2330 * @param start the index of the start of the range to measure 2331 * @param end the index + 1 of the end of the range to measure 2332 * @param contextStart the index of the start of the shaping context 2333 * @param contextEnd the index + 1 of the end of the shaping context 2334 * @param isRtl whether the run is in RTL direction 2335 * @param offset index of caret position 2336 * @return width measurement between start and offset 2337 */ 2338 public float getRunAdvance(char[] text, int start, int end, int contextStart, int contextEnd, 2339 boolean isRtl, int offset) { 2340 if (text == null) { 2341 throw new IllegalArgumentException("text cannot be null"); 2342 } 2343 if ((contextStart | start | offset | end | contextEnd 2344 | start - contextStart | offset - start | end - offset 2345 | contextEnd - end | text.length - contextEnd) < 0) { 2346 throw new IndexOutOfBoundsException(); 2347 } 2348 if (end == start) { 2349 return 0.0f; 2350 } 2351 // TODO: take mCompatScaling into account (or eliminate compat scaling)? 2352 return native_getRunAdvance(mNativePaint, mNativeTypeface, text, start, end, 2353 contextStart, contextEnd, isRtl, offset); 2354 } 2355 2356 /** 2357 * @see #getRunAdvance(char[], int, int, int, int, boolean, int) 2358 * 2359 * @param text the text to measure. Cannot be null. 2360 * @param start the index of the start of the range to measure 2361 * @param end the index + 1 of the end of the range to measure 2362 * @param contextStart the index of the start of the shaping context 2363 * @param contextEnd the index + 1 of the end of the shaping context 2364 * @param isRtl whether the run is in RTL direction 2365 * @param offset index of caret position 2366 * @return width measurement between start and offset 2367 */ 2368 public float getRunAdvance(CharSequence text, int start, int end, int contextStart, 2369 int contextEnd, boolean isRtl, int offset) { 2370 if (text == null) { 2371 throw new IllegalArgumentException("text cannot be null"); 2372 } 2373 if ((contextStart | start | offset | end | contextEnd 2374 | start - contextStart | offset - start | end - offset 2375 | contextEnd - end | text.length() - contextEnd) < 0) { 2376 throw new IndexOutOfBoundsException(); 2377 } 2378 if (end == start) { 2379 return 0.0f; 2380 } 2381 // TODO performance: specialized alternatives to avoid buffer copy, if win is significant 2382 char[] buf = TemporaryBuffer.obtain(contextEnd - contextStart); 2383 TextUtils.getChars(text, contextStart, contextEnd, buf, 0); 2384 float result = getRunAdvance(buf, start - contextStart, end - contextStart, 0, 2385 contextEnd - contextStart, isRtl, offset - contextStart); 2386 TemporaryBuffer.recycle(buf); 2387 return result; 2388 } 2389 2390 /** 2391 * Get the character offset within the string whose position is closest to the specified 2392 * horizontal position. 2393 * 2394 * <p>The returned value is generally the value of {@code offset} for which 2395 * {@link #getRunAdvance} yields a result most closely approximating {@code advance}, 2396 * and which is also on a grapheme cluster boundary. As such, it is the preferred method 2397 * for positioning a cursor in response to a touch or pointer event. The grapheme cluster 2398 * boundaries are based on 2399 * <a href="http://unicode.org/reports/tr29/">Unicode Standard Annex #29</a> but with some 2400 * tailoring for better user experience. 2401 * 2402 * <p>Note that {@code advance} is a (generally positive) width measurement relative to the start 2403 * of the run. Thus, for RTL runs it the distance from the point to the right edge. 2404 * 2405 * <p>All indices are relative to the start of {@code text}. Further, {@code 0 <= contextStart 2406 * <= start <= end <= contextEnd <= text.length} must hold on entry, and {@code start <= result 2407 * <= end} will hold on return. 2408 * 2409 * @param text the text to measure. Cannot be null. 2410 * @param start the index of the start of the range to measure 2411 * @param end the index + 1 of the end of the range to measure 2412 * @param contextStart the index of the start of the shaping context 2413 * @param contextEnd the index + 1 of the end of the range to measure 2414 * @param isRtl whether the run is in RTL direction 2415 * @param advance width relative to start of run 2416 * @return index of offset 2417 */ 2418 public int getOffsetForAdvance(char[] text, int start, int end, int contextStart, 2419 int contextEnd, boolean isRtl, float advance) { 2420 if (text == null) { 2421 throw new IllegalArgumentException("text cannot be null"); 2422 } 2423 if ((contextStart | start | end | contextEnd 2424 | start - contextStart | end - start | contextEnd - end 2425 | text.length - contextEnd) < 0) { 2426 throw new IndexOutOfBoundsException(); 2427 } 2428 // TODO: take mCompatScaling into account (or eliminate compat scaling)? 2429 return native_getOffsetForAdvance(mNativePaint, mNativeTypeface, text, start, end, 2430 contextStart, contextEnd, isRtl, advance); 2431 } 2432 2433 /** 2434 * @see #getOffsetForAdvance(char[], int, int, int, int, boolean, float) 2435 * 2436 * @param text the text to measure. Cannot be null. 2437 * @param start the index of the start of the range to measure 2438 * @param end the index + 1 of the end of the range to measure 2439 * @param contextStart the index of the start of the shaping context 2440 * @param contextEnd the index + 1 of the end of the range to measure 2441 * @param isRtl whether the run is in RTL direction 2442 * @param advance width relative to start of run 2443 * @return index of offset 2444 */ 2445 public int getOffsetForAdvance(CharSequence text, int start, int end, int contextStart, 2446 int contextEnd, boolean isRtl, float advance) { 2447 if (text == null) { 2448 throw new IllegalArgumentException("text cannot be null"); 2449 } 2450 if ((contextStart | start | end | contextEnd 2451 | start - contextStart | end - start | contextEnd - end 2452 | text.length() - contextEnd) < 0) { 2453 throw new IndexOutOfBoundsException(); 2454 } 2455 // TODO performance: specialized alternatives to avoid buffer copy, if win is significant 2456 char[] buf = TemporaryBuffer.obtain(contextEnd - contextStart); 2457 TextUtils.getChars(text, contextStart, contextEnd, buf, 0); 2458 int result = getOffsetForAdvance(buf, start - contextStart, end - contextStart, 0, 2459 contextEnd - contextStart, isRtl, advance) + contextStart; 2460 TemporaryBuffer.recycle(buf); 2461 return result; 2462 } 2463 2464 @Override 2465 protected void finalize() throws Throwable { 2466 try { 2467 finalizer(mNativePaint); 2468 } finally { 2469 super.finalize(); 2470 } 2471 } 2472 2473 private static native long native_init(); 2474 private static native long native_initWithPaint(long paint); 2475 private static native void native_reset(long native_object); 2476 private static native void native_set(long native_dst, long native_src); 2477 private static native int native_getStyle(long native_object); 2478 private static native void native_setStyle(long native_object, int style); 2479 private static native int native_getStrokeCap(long native_object); 2480 private static native void native_setStrokeCap(long native_object, int cap); 2481 private static native int native_getStrokeJoin(long native_object); 2482 private static native void native_setStrokeJoin(long native_object, 2483 int join); 2484 private static native boolean native_getFillPath(long native_object, 2485 long src, long dst); 2486 private static native long native_setShader(long native_object, long shader); 2487 private static native long native_setColorFilter(long native_object, 2488 long filter); 2489 private static native long native_setXfermode(long native_object, 2490 long xfermode); 2491 private static native long native_setPathEffect(long native_object, 2492 long effect); 2493 private static native long native_setMaskFilter(long native_object, 2494 long maskfilter); 2495 private static native long native_setTypeface(long native_object, 2496 long typeface); 2497 private static native long native_setRasterizer(long native_object, 2498 long rasterizer); 2499 2500 private static native int native_getTextAlign(long native_object); 2501 private static native void native_setTextAlign(long native_object, 2502 int align); 2503 2504 private static native void native_setTextLocale(long native_object, 2505 String locale); 2506 2507 private static native int native_getTextGlyphs(long native_object, 2508 String text, int start, int end, int contextStart, int contextEnd, 2509 int flags, char[] glyphs); 2510 2511 private static native float native_getTextAdvances(long native_object, long native_typeface, 2512 char[] text, int index, int count, int contextIndex, int contextCount, 2513 int bidiFlags, float[] advances, int advancesIndex); 2514 private static native float native_getTextAdvances(long native_object, long native_typeface, 2515 String text, int start, int end, int contextStart, int contextEnd, 2516 int bidiFlags, float[] advances, int advancesIndex); 2517 2518 private native int native_getTextRunCursor(long native_object, char[] text, 2519 int contextStart, int contextLength, int dir, int offset, int cursorOpt); 2520 private native int native_getTextRunCursor(long native_object, String text, 2521 int contextStart, int contextEnd, int dir, int offset, int cursorOpt); 2522 2523 private static native void native_getTextPath(long native_object, long native_typeface, 2524 int bidiFlags, char[] text, int index, int count, float x, float y, long path); 2525 private static native void native_getTextPath(long native_object, long native_typeface, 2526 int bidiFlags, String text, int start, int end, float x, float y, long path); 2527 private static native void nativeGetStringBounds(long nativePaint, long native_typeface, 2528 String text, int start, int end, int bidiFlags, Rect bounds); 2529 private static native void nativeGetCharArrayBounds(long nativePaint, long native_typeface, 2530 char[] text, int index, int count, int bidiFlags, Rect bounds); 2531 private static native void finalizer(long nativePaint); 2532 2533 private static native void native_setShadowLayer(long native_object, 2534 float radius, float dx, float dy, int color); 2535 private static native boolean native_hasShadowLayer(long native_object); 2536 2537 private static native float native_getLetterSpacing(long native_object); 2538 private static native void native_setLetterSpacing(long native_object, 2539 float letterSpacing); 2540 private static native void native_setFontFeatureSettings(long native_object, 2541 String settings); 2542 private static native int native_getHyphenEdit(long native_object); 2543 private static native void native_setHyphenEdit(long native_object, int hyphen); 2544 private static native boolean native_hasGlyph(long native_object, long native_typeface, 2545 int bidiFlags, String string); 2546 private static native float native_getRunAdvance(long native_object, long native_typeface, 2547 char[] text, int start, int end, int contextStart, int contextEnd, boolean isRtl, 2548 int offset); 2549 private static native int native_getOffsetForAdvance(long native_object, 2550 long native_typeface, char[] text, int start, int end, int contextStart, int contextEnd, 2551 boolean isRtl, float advance); 2552} 2553