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