Paint.java revision 0f07dd5b14e76695bbae758e948e00b86935232c
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 * Sets TrueType or OpenType font variation settings. The settings string is constructed from 1543 * multiple pairs of axis tag and style values. The axis tag must contain four ASCII characters 1544 * and must be wrapped with single quotes (U+0027) or double quotes (U+0022). Axis strings that 1545 * are longer or shorter than four characters, or contain characters outside of U+0020..U+007E 1546 * are invalid. If a specified axis name is not defined in the font, the settings will be 1547 * ignored. 1548 * 1549 * Examples, 1550 * <ul> 1551 * <li>Set font width to 150. 1552 * <pre> 1553 * <code> 1554 * Paint paint = new Paint(); 1555 * paint.setFontVariationSettings("'wdth' 150"); 1556 * </code> 1557 * </pre> 1558 * </li> 1559 * 1560 * <li>Set the font slant to 20 degrees and ask for italic style. 1561 * <pre> 1562 * <code> 1563 * Paint paint = new Paint(); 1564 * paint.setFontVariationSettings("'slnt' 20, 'ital' 1"); 1565 * </code> 1566 * </pre> 1567 * </li> 1568 * </ul> 1569 * 1570 * @param fontVariationSettings font variation settings. You can pass null or empty string as 1571 * no variation settings. 1572 * 1573 * @return true if the given settings is effective to at least one font file underlying this 1574 * typeface. This function also returns true for empty settings string. Otherwise 1575 * returns false 1576 * 1577 * @throws IllegalArgumentException If given string is not a valid font variation settings 1578 * format 1579 * 1580 * @see #getFontVariationSettings() 1581 * @see FontVariationAxis 1582 */ 1583 public boolean setFontVariationSettings(String fontVariationSettings) { 1584 final String settings = TextUtils.nullIfEmpty(fontVariationSettings); 1585 if (settings == mFontVariationSettings 1586 || (settings != null && settings.equals(mFontVariationSettings))) { 1587 return true; 1588 } 1589 1590 if (settings == null || settings.length() == 0) { 1591 mFontVariationSettings = null; 1592 setTypeface(Typeface.createFromTypefaceWithVariation(mTypeface, 1593 Collections.emptyList())); 1594 return true; 1595 } 1596 1597 FontVariationAxis[] axes = FontVariationAxis.fromFontVariationSettings(settings); 1598 final ArrayList<FontVariationAxis> filteredAxes = new ArrayList<FontVariationAxis>(); 1599 for (final FontVariationAxis axis : axes) { 1600 if (mTypeface.isSupportedAxes(axis.getOpenTypeTagValue())) { 1601 filteredAxes.add(axis); 1602 } 1603 } 1604 if (filteredAxes.isEmpty()) { 1605 return false; 1606 } 1607 mFontVariationSettings = settings; 1608 setTypeface(Typeface.createFromTypefaceWithVariation(mTypeface, filteredAxes)); 1609 return true; 1610 } 1611 1612 /** 1613 * Get the current value of hyphen edit. 1614 * 1615 * @return the current hyphen edit value 1616 * 1617 * @hide 1618 */ 1619 public int getHyphenEdit() { 1620 return nGetHyphenEdit(mNativePaint); 1621 } 1622 1623 /** 1624 * Set a hyphen edit on the paint (causes a hyphen to be added to text when 1625 * measured or drawn). 1626 * 1627 * @param hyphen 0 for no edit, 1 for adding a hyphen at the end, etc. 1628 * Definition of various values are in the HyphenEdit class in Minikin's Hyphenator.h. 1629 * 1630 * @hide 1631 */ 1632 public void setHyphenEdit(int hyphen) { 1633 nSetHyphenEdit(mNativePaint, hyphen); 1634 } 1635 1636 /** 1637 * Return the distance above (negative) the baseline (ascent) based on the 1638 * current typeface and text size. 1639 * 1640 * @return the distance above (negative) the baseline (ascent) based on the 1641 * current typeface and text size. 1642 */ 1643 public float ascent() { 1644 return nAscent(mNativePaint, mNativeTypeface); 1645 } 1646 1647 /** 1648 * Return the distance below (positive) the baseline (descent) based on the 1649 * current typeface and text size. 1650 * 1651 * @return the distance below (positive) the baseline (descent) based on 1652 * the current typeface and text size. 1653 */ 1654 public float descent() { 1655 return nDescent(mNativePaint, mNativeTypeface); 1656 } 1657 1658 /** 1659 * Class that describes the various metrics for a font at a given text size. 1660 * Remember, Y values increase going down, so those values will be positive, 1661 * and values that measure distances going up will be negative. This class 1662 * is returned by getFontMetrics(). 1663 */ 1664 public static class FontMetrics { 1665 /** 1666 * The maximum distance above the baseline for the tallest glyph in 1667 * the font at a given text size. 1668 */ 1669 public float top; 1670 /** 1671 * The recommended distance above the baseline for singled spaced text. 1672 */ 1673 public float ascent; 1674 /** 1675 * The recommended distance below the baseline for singled spaced text. 1676 */ 1677 public float descent; 1678 /** 1679 * The maximum distance below the baseline for the lowest glyph in 1680 * the font at a given text size. 1681 */ 1682 public float bottom; 1683 /** 1684 * The recommended additional space to add between lines of text. 1685 */ 1686 public float leading; 1687 } 1688 1689 /** 1690 * Return the font's recommended interline spacing, given the Paint's 1691 * settings for typeface, textSize, etc. If metrics is not null, return the 1692 * fontmetric values in it. 1693 * 1694 * @param metrics If this object is not null, its fields are filled with 1695 * the appropriate values given the paint's text attributes. 1696 * @return the font's recommended interline spacing. 1697 */ 1698 public float getFontMetrics(FontMetrics metrics) { 1699 return nGetFontMetrics(mNativePaint, mNativeTypeface, metrics); 1700 } 1701 1702 /** 1703 * Allocates a new FontMetrics object, and then calls getFontMetrics(fm) 1704 * with it, returning the object. 1705 */ 1706 public FontMetrics getFontMetrics() { 1707 FontMetrics fm = new FontMetrics(); 1708 getFontMetrics(fm); 1709 return fm; 1710 } 1711 1712 /** 1713 * Convenience method for callers that want to have FontMetrics values as 1714 * integers. 1715 */ 1716 public static class FontMetricsInt { 1717 /** 1718 * The maximum distance above the baseline for the tallest glyph in 1719 * the font at a given text size. 1720 */ 1721 public int top; 1722 /** 1723 * The recommended distance above the baseline for singled spaced text. 1724 */ 1725 public int ascent; 1726 /** 1727 * The recommended distance below the baseline for singled spaced text. 1728 */ 1729 public int descent; 1730 /** 1731 * The maximum distance below the baseline for the lowest glyph in 1732 * the font at a given text size. 1733 */ 1734 public int bottom; 1735 /** 1736 * The recommended additional space to add between lines of text. 1737 */ 1738 public int leading; 1739 1740 @Override public String toString() { 1741 return "FontMetricsInt: top=" + top + " ascent=" + ascent + 1742 " descent=" + descent + " bottom=" + bottom + 1743 " leading=" + leading; 1744 } 1745 } 1746 1747 /** 1748 * Return the font's interline spacing, given the Paint's settings for 1749 * typeface, textSize, etc. If metrics is not null, return the fontmetric 1750 * values in it. Note: all values have been converted to integers from 1751 * floats, in such a way has to make the answers useful for both spacing 1752 * and clipping. If you want more control over the rounding, call 1753 * getFontMetrics(). 1754 * 1755 * @return the font's interline spacing. 1756 */ 1757 public int getFontMetricsInt(FontMetricsInt fmi) { 1758 return nGetFontMetricsInt(mNativePaint, mNativeTypeface, fmi); 1759 } 1760 1761 public FontMetricsInt getFontMetricsInt() { 1762 FontMetricsInt fm = new FontMetricsInt(); 1763 getFontMetricsInt(fm); 1764 return fm; 1765 } 1766 1767 /** 1768 * Return the recommend line spacing based on the current typeface and 1769 * text size. 1770 * 1771 * @return recommend line spacing based on the current typeface and 1772 * text size. 1773 */ 1774 public float getFontSpacing() { 1775 return getFontMetrics(null); 1776 } 1777 1778 /** 1779 * Return the width of the text. 1780 * 1781 * @param text The text to measure. Cannot be null. 1782 * @param index The index of the first character to start measuring 1783 * @param count THe number of characters to measure, beginning with start 1784 * @return The width of the text 1785 */ 1786 public float measureText(char[] text, int index, int count) { 1787 if (text == null) { 1788 throw new IllegalArgumentException("text cannot be null"); 1789 } 1790 if ((index | count) < 0 || index + count > text.length) { 1791 throw new ArrayIndexOutOfBoundsException(); 1792 } 1793 1794 if (text.length == 0 || count == 0) { 1795 return 0f; 1796 } 1797 if (!mHasCompatScaling) { 1798 return (float) Math.ceil(nGetTextAdvances(mNativePaint, mNativeTypeface, text, 1799 index, count, index, count, mBidiFlags, null, 0)); 1800 } 1801 1802 final float oldSize = getTextSize(); 1803 setTextSize(oldSize * mCompatScaling); 1804 float w = nGetTextAdvances(mNativePaint, mNativeTypeface, text, index, count, index, 1805 count, mBidiFlags, null, 0); 1806 setTextSize(oldSize); 1807 return (float) Math.ceil(w*mInvCompatScaling); 1808 } 1809 1810 /** 1811 * Return the width of the text. 1812 * 1813 * @param text The text to measure. Cannot be null. 1814 * @param start The index of the first character to start measuring 1815 * @param end 1 beyond the index of the last character to measure 1816 * @return The width of the text 1817 */ 1818 public float measureText(String text, int start, int end) { 1819 if (text == null) { 1820 throw new IllegalArgumentException("text cannot be null"); 1821 } 1822 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1823 throw new IndexOutOfBoundsException(); 1824 } 1825 1826 if (text.length() == 0 || start == end) { 1827 return 0f; 1828 } 1829 if (!mHasCompatScaling) { 1830 return (float) Math.ceil(nGetTextAdvances(mNativePaint, mNativeTypeface, text, 1831 start, end, start, end, mBidiFlags, null, 0)); 1832 } 1833 final float oldSize = getTextSize(); 1834 setTextSize(oldSize * mCompatScaling); 1835 float w = nGetTextAdvances(mNativePaint, mNativeTypeface, text, start, end, start, 1836 end, mBidiFlags, null, 0); 1837 setTextSize(oldSize); 1838 return (float) Math.ceil(w * mInvCompatScaling); 1839 } 1840 1841 /** 1842 * Return the width of the text. 1843 * 1844 * @param text The text to measure. Cannot be null. 1845 * @return The width of the text 1846 */ 1847 public float measureText(String text) { 1848 if (text == null) { 1849 throw new IllegalArgumentException("text cannot be null"); 1850 } 1851 return measureText(text, 0, text.length()); 1852 } 1853 1854 /** 1855 * Return the width of the text. 1856 * 1857 * @param text The text to measure 1858 * @param start The index of the first character to start measuring 1859 * @param end 1 beyond the index of the last character to measure 1860 * @return The width of the text 1861 */ 1862 public float measureText(CharSequence text, int start, int end) { 1863 if (text == null) { 1864 throw new IllegalArgumentException("text cannot be null"); 1865 } 1866 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1867 throw new IndexOutOfBoundsException(); 1868 } 1869 1870 if (text.length() == 0 || start == end) { 1871 return 0f; 1872 } 1873 if (text instanceof String) { 1874 return measureText((String)text, start, end); 1875 } 1876 if (text instanceof SpannedString || 1877 text instanceof SpannableString) { 1878 return measureText(text.toString(), start, end); 1879 } 1880 if (text instanceof GraphicsOperations) { 1881 return ((GraphicsOperations)text).measureText(start, end, this); 1882 } 1883 1884 char[] buf = TemporaryBuffer.obtain(end - start); 1885 TextUtils.getChars(text, start, end, buf, 0); 1886 float result = measureText(buf, 0, end - start); 1887 TemporaryBuffer.recycle(buf); 1888 return result; 1889 } 1890 1891 /** 1892 * Measure the text, stopping early if the measured width exceeds maxWidth. 1893 * Return the number of chars that were measured, and if measuredWidth is 1894 * not null, return in it the actual width measured. 1895 * 1896 * @param text The text to measure. Cannot be null. 1897 * @param index The offset into text to begin measuring at 1898 * @param count The number of maximum number of entries to measure. If count 1899 * is negative, then the characters are measured in reverse order. 1900 * @param maxWidth The maximum width to accumulate. 1901 * @param measuredWidth Optional. If not null, returns the actual width 1902 * measured. 1903 * @return The number of chars that were measured. Will always be <= 1904 * abs(count). 1905 */ 1906 public int breakText(char[] text, int index, int count, 1907 float maxWidth, float[] measuredWidth) { 1908 if (text == null) { 1909 throw new IllegalArgumentException("text cannot be null"); 1910 } 1911 if (index < 0 || text.length - index < Math.abs(count)) { 1912 throw new ArrayIndexOutOfBoundsException(); 1913 } 1914 1915 if (text.length == 0 || count == 0) { 1916 return 0; 1917 } 1918 if (!mHasCompatScaling) { 1919 return nBreakText(mNativePaint, mNativeTypeface, text, index, count, maxWidth, 1920 mBidiFlags, measuredWidth); 1921 } 1922 1923 final float oldSize = getTextSize(); 1924 setTextSize(oldSize * mCompatScaling); 1925 int res = nBreakText(mNativePaint, mNativeTypeface, text, index, count, 1926 maxWidth * mCompatScaling, mBidiFlags, measuredWidth); 1927 setTextSize(oldSize); 1928 if (measuredWidth != null) measuredWidth[0] *= mInvCompatScaling; 1929 return res; 1930 } 1931 1932 /** 1933 * Measure the text, stopping early if the measured width exceeds maxWidth. 1934 * Return the number of chars that were measured, and if measuredWidth is 1935 * not null, return in it the actual width measured. 1936 * 1937 * @param text The text to measure. Cannot be null. 1938 * @param start The offset into text to begin measuring at 1939 * @param end The end of the text slice to measure. 1940 * @param measureForwards If true, measure forwards, starting at start. 1941 * Otherwise, measure backwards, starting with end. 1942 * @param maxWidth The maximum width to accumulate. 1943 * @param measuredWidth Optional. If not null, returns the actual width 1944 * measured. 1945 * @return The number of chars that were measured. Will always be <= 1946 * abs(end - start). 1947 */ 1948 public int breakText(CharSequence text, int start, int end, 1949 boolean measureForwards, 1950 float maxWidth, float[] measuredWidth) { 1951 if (text == null) { 1952 throw new IllegalArgumentException("text cannot be null"); 1953 } 1954 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1955 throw new IndexOutOfBoundsException(); 1956 } 1957 1958 if (text.length() == 0 || start == end) { 1959 return 0; 1960 } 1961 if (start == 0 && text instanceof String && end == text.length()) { 1962 return breakText((String) text, measureForwards, maxWidth, 1963 measuredWidth); 1964 } 1965 1966 char[] buf = TemporaryBuffer.obtain(end - start); 1967 int result; 1968 1969 TextUtils.getChars(text, start, end, buf, 0); 1970 1971 if (measureForwards) { 1972 result = breakText(buf, 0, end - start, maxWidth, measuredWidth); 1973 } else { 1974 result = breakText(buf, 0, -(end - start), maxWidth, measuredWidth); 1975 } 1976 1977 TemporaryBuffer.recycle(buf); 1978 return result; 1979 } 1980 1981 /** 1982 * Measure the text, stopping early if the measured width exceeds maxWidth. 1983 * Return the number of chars that were measured, and if measuredWidth is 1984 * not null, return in it the actual width measured. 1985 * 1986 * @param text The text to measure. Cannot be null. 1987 * @param measureForwards If true, measure forwards, starting with the 1988 * first character in the string. Otherwise, 1989 * measure backwards, starting with the 1990 * last character in the string. 1991 * @param maxWidth The maximum width to accumulate. 1992 * @param measuredWidth Optional. If not null, returns the actual width 1993 * measured. 1994 * @return The number of chars that were measured. Will always be <= 1995 * abs(count). 1996 */ 1997 public int breakText(String text, boolean measureForwards, 1998 float maxWidth, float[] measuredWidth) { 1999 if (text == null) { 2000 throw new IllegalArgumentException("text cannot be null"); 2001 } 2002 2003 if (text.length() == 0) { 2004 return 0; 2005 } 2006 if (!mHasCompatScaling) { 2007 return nBreakText(mNativePaint, mNativeTypeface, text, measureForwards, 2008 maxWidth, mBidiFlags, measuredWidth); 2009 } 2010 2011 final float oldSize = getTextSize(); 2012 setTextSize(oldSize*mCompatScaling); 2013 int res = nBreakText(mNativePaint, mNativeTypeface, text, measureForwards, 2014 maxWidth*mCompatScaling, mBidiFlags, measuredWidth); 2015 setTextSize(oldSize); 2016 if (measuredWidth != null) measuredWidth[0] *= mInvCompatScaling; 2017 return res; 2018 } 2019 2020 /** 2021 * Return the advance widths for the characters in the string. 2022 * 2023 * @param text The text to measure. Cannot be null. 2024 * @param index The index of the first char to to measure 2025 * @param count The number of chars starting with index to measure 2026 * @param widths array to receive the advance widths of the characters. 2027 * Must be at least a large as count. 2028 * @return the actual number of widths returned. 2029 */ 2030 public int getTextWidths(char[] text, int index, int count, 2031 float[] widths) { 2032 if (text == null) { 2033 throw new IllegalArgumentException("text cannot be null"); 2034 } 2035 if ((index | count) < 0 || index + count > text.length 2036 || count > widths.length) { 2037 throw new ArrayIndexOutOfBoundsException(); 2038 } 2039 2040 if (text.length == 0 || count == 0) { 2041 return 0; 2042 } 2043 if (!mHasCompatScaling) { 2044 nGetTextAdvances(mNativePaint, mNativeTypeface, text, index, count, index, count, 2045 mBidiFlags, widths, 0); 2046 return count; 2047 } 2048 2049 final float oldSize = getTextSize(); 2050 setTextSize(oldSize * mCompatScaling); 2051 nGetTextAdvances(mNativePaint, mNativeTypeface, text, index, count, index, count, 2052 mBidiFlags, widths, 0); 2053 setTextSize(oldSize); 2054 for (int i = 0; i < count; i++) { 2055 widths[i] *= mInvCompatScaling; 2056 } 2057 return count; 2058 } 2059 2060 /** 2061 * Return the advance widths for the characters in the string. 2062 * 2063 * @param text The text to measure. Cannot be null. 2064 * @param start The index of the first char to to measure 2065 * @param end The end of the text slice to measure 2066 * @param widths array to receive the advance widths of the characters. 2067 * Must be at least a large as (end - start). 2068 * @return the actual number of widths returned. 2069 */ 2070 public int getTextWidths(CharSequence text, int start, int end, 2071 float[] widths) { 2072 if (text == null) { 2073 throw new IllegalArgumentException("text cannot be null"); 2074 } 2075 if ((start | end | (end - start) | (text.length() - end)) < 0) { 2076 throw new IndexOutOfBoundsException(); 2077 } 2078 if (end - start > widths.length) { 2079 throw new ArrayIndexOutOfBoundsException(); 2080 } 2081 2082 if (text.length() == 0 || start == end) { 2083 return 0; 2084 } 2085 if (text instanceof String) { 2086 return getTextWidths((String) text, start, end, widths); 2087 } 2088 if (text instanceof SpannedString || 2089 text instanceof SpannableString) { 2090 return getTextWidths(text.toString(), start, end, widths); 2091 } 2092 if (text instanceof GraphicsOperations) { 2093 return ((GraphicsOperations) text).getTextWidths(start, end, 2094 widths, this); 2095 } 2096 2097 char[] buf = TemporaryBuffer.obtain(end - start); 2098 TextUtils.getChars(text, start, end, buf, 0); 2099 int result = getTextWidths(buf, 0, end - start, widths); 2100 TemporaryBuffer.recycle(buf); 2101 return result; 2102 } 2103 2104 /** 2105 * Return the advance widths for the characters in the string. 2106 * 2107 * @param text The text to measure. Cannot be null. 2108 * @param start The index of the first char to to measure 2109 * @param end The end of the text slice to measure 2110 * @param widths array to receive the advance widths of the characters. 2111 * Must be at least a large as the text. 2112 * @return the number of code units in the specified text. 2113 */ 2114 public int getTextWidths(String text, int start, int end, float[] widths) { 2115 if (text == null) { 2116 throw new IllegalArgumentException("text cannot be null"); 2117 } 2118 if ((start | end | (end - start) | (text.length() - end)) < 0) { 2119 throw new IndexOutOfBoundsException(); 2120 } 2121 if (end - start > widths.length) { 2122 throw new ArrayIndexOutOfBoundsException(); 2123 } 2124 2125 if (text.length() == 0 || start == end) { 2126 return 0; 2127 } 2128 if (!mHasCompatScaling) { 2129 nGetTextAdvances(mNativePaint, mNativeTypeface, text, start, end, start, end, 2130 mBidiFlags, widths, 0); 2131 return end - start; 2132 } 2133 2134 final float oldSize = getTextSize(); 2135 setTextSize(oldSize * mCompatScaling); 2136 nGetTextAdvances(mNativePaint, mNativeTypeface, text, start, end, start, end, 2137 mBidiFlags, widths, 0); 2138 setTextSize(oldSize); 2139 for (int i = 0; i < end - start; i++) { 2140 widths[i] *= mInvCompatScaling; 2141 } 2142 return end - start; 2143 } 2144 2145 /** 2146 * Return the advance widths for the characters in the string. 2147 * 2148 * @param text The text to measure 2149 * @param widths array to receive the advance widths of the characters. 2150 * Must be at least a large as the text. 2151 * @return the number of code units in the specified text. 2152 */ 2153 public int getTextWidths(String text, float[] widths) { 2154 return getTextWidths(text, 0, text.length(), widths); 2155 } 2156 2157 /** 2158 * Convenience overload that takes a char array instead of a 2159 * String. 2160 * 2161 * @see #getTextRunAdvances(String, int, int, int, int, boolean, float[], int) 2162 * @hide 2163 */ 2164 public float getTextRunAdvances(char[] chars, int index, int count, 2165 int contextIndex, int contextCount, boolean isRtl, float[] advances, 2166 int advancesIndex) { 2167 2168 if (chars == null) { 2169 throw new IllegalArgumentException("text cannot be null"); 2170 } 2171 if ((index | count | contextIndex | contextCount | advancesIndex 2172 | (index - contextIndex) | (contextCount - count) 2173 | ((contextIndex + contextCount) - (index + count)) 2174 | (chars.length - (contextIndex + contextCount)) 2175 | (advances == null ? 0 : 2176 (advances.length - (advancesIndex + count)))) < 0) { 2177 throw new IndexOutOfBoundsException(); 2178 } 2179 2180 if (chars.length == 0 || count == 0){ 2181 return 0f; 2182 } 2183 if (!mHasCompatScaling) { 2184 return nGetTextAdvances(mNativePaint, mNativeTypeface, chars, index, count, 2185 contextIndex, contextCount, isRtl ? BIDI_FORCE_RTL : BIDI_FORCE_LTR, advances, 2186 advancesIndex); 2187 } 2188 2189 final float oldSize = getTextSize(); 2190 setTextSize(oldSize * mCompatScaling); 2191 float res = nGetTextAdvances(mNativePaint, mNativeTypeface, chars, index, count, 2192 contextIndex, contextCount, isRtl ? BIDI_FORCE_RTL : BIDI_FORCE_LTR, advances, 2193 advancesIndex); 2194 setTextSize(oldSize); 2195 2196 if (advances != null) { 2197 for (int i = advancesIndex, e = i + count; i < e; i++) { 2198 advances[i] *= mInvCompatScaling; 2199 } 2200 } 2201 return res * mInvCompatScaling; // assume errors are not significant 2202 } 2203 2204 /** 2205 * Convenience overload that takes a CharSequence instead of a 2206 * String. 2207 * 2208 * @see #getTextRunAdvances(String, int, int, int, int, boolean, float[], int) 2209 * @hide 2210 */ 2211 public float getTextRunAdvances(CharSequence text, int start, int end, 2212 int contextStart, int contextEnd, boolean isRtl, float[] advances, 2213 int advancesIndex) { 2214 if (text == null) { 2215 throw new IllegalArgumentException("text cannot be null"); 2216 } 2217 if ((start | end | contextStart | contextEnd | advancesIndex | (end - start) 2218 | (start - contextStart) | (contextEnd - end) 2219 | (text.length() - contextEnd) 2220 | (advances == null ? 0 : 2221 (advances.length - advancesIndex - (end - start)))) < 0) { 2222 throw new IndexOutOfBoundsException(); 2223 } 2224 2225 if (text instanceof String) { 2226 return getTextRunAdvances((String) text, start, end, 2227 contextStart, contextEnd, isRtl, advances, advancesIndex); 2228 } 2229 if (text instanceof SpannedString || 2230 text instanceof SpannableString) { 2231 return getTextRunAdvances(text.toString(), start, end, 2232 contextStart, contextEnd, isRtl, advances, advancesIndex); 2233 } 2234 if (text instanceof GraphicsOperations) { 2235 return ((GraphicsOperations) text).getTextRunAdvances(start, end, 2236 contextStart, contextEnd, isRtl, advances, advancesIndex, this); 2237 } 2238 if (text.length() == 0 || end == start) { 2239 return 0f; 2240 } 2241 2242 int contextLen = contextEnd - contextStart; 2243 int len = end - start; 2244 char[] buf = TemporaryBuffer.obtain(contextLen); 2245 TextUtils.getChars(text, contextStart, contextEnd, buf, 0); 2246 float result = getTextRunAdvances(buf, start - contextStart, len, 2247 0, contextLen, isRtl, advances, advancesIndex); 2248 TemporaryBuffer.recycle(buf); 2249 return result; 2250 } 2251 2252 /** 2253 * Returns the total advance width for the characters in the run 2254 * between start and end, and if advances is not null, the advance 2255 * assigned to each of these characters (java chars). 2256 * 2257 * <p>The trailing surrogate in a valid surrogate pair is assigned 2258 * an advance of 0. Thus the number of returned advances is 2259 * always equal to count, not to the number of unicode codepoints 2260 * represented by the run. 2261 * 2262 * <p>In the case of conjuncts or combining marks, the total 2263 * advance is assigned to the first logical character, and the 2264 * following characters are assigned an advance of 0. 2265 * 2266 * <p>This generates the sum of the advances of glyphs for 2267 * characters in a reordered cluster as the width of the first 2268 * logical character in the cluster, and 0 for the widths of all 2269 * other characters in the cluster. In effect, such clusters are 2270 * treated like conjuncts. 2271 * 2272 * <p>The shaping bounds limit the amount of context available 2273 * outside start and end that can be used for shaping analysis. 2274 * These bounds typically reflect changes in bidi level or font 2275 * metrics across which shaping does not occur. 2276 * 2277 * @param text the text to measure. Cannot be null. 2278 * @param start the index of the first character to measure 2279 * @param end the index past the last character to measure 2280 * @param contextStart the index of the first character to use for shaping context, 2281 * must be <= start 2282 * @param contextEnd the index past the last character to use for shaping context, 2283 * must be >= end 2284 * @param isRtl whether the run is in RTL direction 2285 * @param advances array to receive the advances, must have room for all advances, 2286 * can be null if only total advance is needed 2287 * @param advancesIndex the position in advances at which to put the 2288 * advance corresponding to the character at start 2289 * @return the total advance 2290 * 2291 * @hide 2292 */ 2293 public float getTextRunAdvances(String text, int start, int end, int contextStart, 2294 int contextEnd, boolean isRtl, float[] advances, int advancesIndex) { 2295 if (text == null) { 2296 throw new IllegalArgumentException("text cannot be null"); 2297 } 2298 if ((start | end | contextStart | contextEnd | advancesIndex | (end - start) 2299 | (start - contextStart) | (contextEnd - end) 2300 | (text.length() - contextEnd) 2301 | (advances == null ? 0 : 2302 (advances.length - advancesIndex - (end - start)))) < 0) { 2303 throw new IndexOutOfBoundsException(); 2304 } 2305 2306 if (text.length() == 0 || start == end) { 2307 return 0f; 2308 } 2309 2310 if (!mHasCompatScaling) { 2311 return nGetTextAdvances(mNativePaint, mNativeTypeface, text, start, end, 2312 contextStart, contextEnd, isRtl ? BIDI_FORCE_RTL : BIDI_FORCE_LTR, advances, 2313 advancesIndex); 2314 } 2315 2316 final float oldSize = getTextSize(); 2317 setTextSize(oldSize * mCompatScaling); 2318 float totalAdvance = nGetTextAdvances(mNativePaint, mNativeTypeface, text, start, 2319 end, contextStart, contextEnd, isRtl ? BIDI_FORCE_RTL : BIDI_FORCE_LTR, advances, 2320 advancesIndex); 2321 setTextSize(oldSize); 2322 2323 if (advances != null) { 2324 for (int i = advancesIndex, e = i + (end - start); i < e; i++) { 2325 advances[i] *= mInvCompatScaling; 2326 } 2327 } 2328 return totalAdvance * mInvCompatScaling; // assume errors are insignificant 2329 } 2330 2331 /** 2332 * Returns the next cursor position in the run. This avoids placing the 2333 * cursor between surrogates, between characters that form conjuncts, 2334 * between base characters and combining marks, or within a reordering 2335 * cluster. 2336 * 2337 * <p>ContextStart and offset are relative to the start of text. 2338 * The context is the shaping context for cursor movement, generally 2339 * the bounds of the metric span enclosing the cursor in the direction of 2340 * movement. 2341 * 2342 * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid 2343 * cursor position, this returns -1. Otherwise this will never return a 2344 * value before contextStart or after contextStart + contextLength. 2345 * 2346 * @param text the text 2347 * @param contextStart the start of the context 2348 * @param contextLength the length of the context 2349 * @param dir either {@link #DIRECTION_RTL} or {@link #DIRECTION_LTR} 2350 * @param offset the cursor position to move from 2351 * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER}, 2352 * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE}, 2353 * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT} 2354 * @return the offset of the next position, or -1 2355 * @hide 2356 */ 2357 public int getTextRunCursor(char[] text, int contextStart, int contextLength, 2358 int dir, int offset, int cursorOpt) { 2359 int contextEnd = contextStart + contextLength; 2360 if (((contextStart | contextEnd | offset | (contextEnd - contextStart) 2361 | (offset - contextStart) | (contextEnd - offset) 2362 | (text.length - contextEnd) | cursorOpt) < 0) 2363 || cursorOpt > CURSOR_OPT_MAX_VALUE) { 2364 throw new IndexOutOfBoundsException(); 2365 } 2366 2367 return nGetTextRunCursor(mNativePaint, mNativeTypeface, text, 2368 contextStart, contextLength, dir, offset, cursorOpt); 2369 } 2370 2371 /** 2372 * Returns the next cursor position in the run. This avoids placing the 2373 * cursor between surrogates, between characters that form conjuncts, 2374 * between base characters and combining marks, or within a reordering 2375 * cluster. 2376 * 2377 * <p>ContextStart, contextEnd, and offset are relative to the start of 2378 * text. The context is the shaping context for cursor movement, generally 2379 * the bounds of the metric span enclosing the cursor in the direction of 2380 * movement. 2381 * 2382 * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid 2383 * cursor position, this returns -1. Otherwise this will never return a 2384 * value before contextStart or after contextEnd. 2385 * 2386 * @param text the text 2387 * @param contextStart the start of the context 2388 * @param contextEnd the end of the context 2389 * @param dir either {@link #DIRECTION_RTL} or {@link #DIRECTION_LTR} 2390 * @param offset the cursor position to move from 2391 * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER}, 2392 * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE}, 2393 * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT} 2394 * @return the offset of the next position, or -1 2395 * @hide 2396 */ 2397 public int getTextRunCursor(CharSequence text, int contextStart, 2398 int contextEnd, int dir, int offset, int cursorOpt) { 2399 2400 if (text instanceof String || text instanceof SpannedString || 2401 text instanceof SpannableString) { 2402 return getTextRunCursor(text.toString(), contextStart, contextEnd, 2403 dir, offset, cursorOpt); 2404 } 2405 if (text instanceof GraphicsOperations) { 2406 return ((GraphicsOperations) text).getTextRunCursor( 2407 contextStart, contextEnd, dir, offset, cursorOpt, this); 2408 } 2409 2410 int contextLen = contextEnd - contextStart; 2411 char[] buf = TemporaryBuffer.obtain(contextLen); 2412 TextUtils.getChars(text, contextStart, contextEnd, buf, 0); 2413 int relPos = getTextRunCursor(buf, 0, contextLen, dir, offset - contextStart, cursorOpt); 2414 TemporaryBuffer.recycle(buf); 2415 return (relPos == -1) ? -1 : relPos + contextStart; 2416 } 2417 2418 /** 2419 * Returns the next cursor position in the run. This avoids placing the 2420 * cursor between surrogates, between characters that form conjuncts, 2421 * between base characters and combining marks, or within a reordering 2422 * cluster. 2423 * 2424 * <p>ContextStart, contextEnd, and offset are relative to the start of 2425 * text. The context is the shaping context for cursor movement, generally 2426 * the bounds of the metric span enclosing the cursor in the direction of 2427 * movement. 2428 * 2429 * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid 2430 * cursor position, this returns -1. Otherwise this will never return a 2431 * value before contextStart or after contextEnd. 2432 * 2433 * @param text the text 2434 * @param contextStart the start of the context 2435 * @param contextEnd the end of the context 2436 * @param dir either {@link #DIRECTION_RTL} or {@link #DIRECTION_LTR} 2437 * @param offset the cursor position to move from 2438 * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER}, 2439 * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE}, 2440 * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT} 2441 * @return the offset of the next position, or -1 2442 * @hide 2443 */ 2444 public int getTextRunCursor(String text, int contextStart, int contextEnd, 2445 int dir, int offset, int cursorOpt) { 2446 if (((contextStart | contextEnd | offset | (contextEnd - contextStart) 2447 | (offset - contextStart) | (contextEnd - offset) 2448 | (text.length() - contextEnd) | cursorOpt) < 0) 2449 || cursorOpt > CURSOR_OPT_MAX_VALUE) { 2450 throw new IndexOutOfBoundsException(); 2451 } 2452 2453 return nGetTextRunCursor(mNativePaint, mNativeTypeface, text, 2454 contextStart, contextEnd, dir, offset, cursorOpt); 2455 } 2456 2457 /** 2458 * Return the path (outline) for the specified text. 2459 * Note: just like Canvas.drawText, this will respect the Align setting in 2460 * the paint. 2461 * 2462 * @param text the text to retrieve the path from 2463 * @param index the index of the first character in text 2464 * @param count the number of characters starting with index 2465 * @param x the x coordinate of the text's origin 2466 * @param y the y coordinate of the text's origin 2467 * @param path the path to receive the data describing the text. Must be allocated by the caller 2468 */ 2469 public void getTextPath(char[] text, int index, int count, 2470 float x, float y, Path path) { 2471 if ((index | count) < 0 || index + count > text.length) { 2472 throw new ArrayIndexOutOfBoundsException(); 2473 } 2474 nGetTextPath(mNativePaint, mNativeTypeface, mBidiFlags, text, index, count, x, y, 2475 path.mutateNI()); 2476 } 2477 2478 /** 2479 * Return the path (outline) for the specified text. 2480 * Note: just like Canvas.drawText, this will respect the Align setting 2481 * in the paint. 2482 * 2483 * @param text the text to retrieve the path from 2484 * @param start the first character in the text 2485 * @param end 1 past the last character in the text 2486 * @param x the x coordinate of the text's origin 2487 * @param y the y coordinate of the text's origin 2488 * @param path the path to receive the data describing the text. Must be allocated by the caller 2489 */ 2490 public void getTextPath(String text, int start, int end, 2491 float x, float y, Path path) { 2492 if ((start | end | (end - start) | (text.length() - end)) < 0) { 2493 throw new IndexOutOfBoundsException(); 2494 } 2495 nGetTextPath(mNativePaint, mNativeTypeface, mBidiFlags, text, start, end, x, y, 2496 path.mutateNI()); 2497 } 2498 2499 /** 2500 * Return in bounds (allocated by the caller) the smallest rectangle that 2501 * encloses all of the characters, with an implied origin at (0,0). 2502 * 2503 * @param text string to measure and return its bounds 2504 * @param start index of the first char in the string to measure 2505 * @param end 1 past the last char in the string to measure 2506 * @param bounds returns the unioned bounds of all the text. Must be allocated by the caller 2507 */ 2508 public void getTextBounds(String text, int start, int end, Rect bounds) { 2509 if ((start | end | (end - start) | (text.length() - end)) < 0) { 2510 throw new IndexOutOfBoundsException(); 2511 } 2512 if (bounds == null) { 2513 throw new NullPointerException("need bounds Rect"); 2514 } 2515 nGetStringBounds(mNativePaint, mNativeTypeface, text, start, end, mBidiFlags, bounds); 2516 } 2517 2518 /** 2519 * Return in bounds (allocated by the caller) the smallest rectangle that 2520 * encloses all of the characters, with an implied origin at (0,0). 2521 * 2522 * @param text text to measure and return its bounds 2523 * @param start index of the first char in the text to measure 2524 * @param end 1 past the last char in the text to measure 2525 * @param bounds returns the unioned bounds of all the text. Must be allocated by the caller 2526 * @hide 2527 */ 2528 public void getTextBounds(CharSequence text, int start, int end, Rect bounds) { 2529 if ((start | end | (end - start) | (text.length() - end)) < 0) { 2530 throw new IndexOutOfBoundsException(); 2531 } 2532 if (bounds == null) { 2533 throw new NullPointerException("need bounds Rect"); 2534 } 2535 char[] buf = TemporaryBuffer.obtain(end - start); 2536 TextUtils.getChars(text, start, end, buf, 0); 2537 getTextBounds(buf, 0, end - start, bounds); 2538 TemporaryBuffer.recycle(buf); 2539 } 2540 2541 /** 2542 * Return in bounds (allocated by the caller) the smallest rectangle that 2543 * encloses all of the characters, with an implied origin at (0,0). 2544 * 2545 * @param text array of chars to measure and return their unioned bounds 2546 * @param index index of the first char in the array to measure 2547 * @param count the number of chars, beginning at index, to measure 2548 * @param bounds returns the unioned bounds of all the text. Must be allocated by the caller 2549 */ 2550 public void getTextBounds(char[] text, int index, int count, Rect bounds) { 2551 if ((index | count) < 0 || index + count > text.length) { 2552 throw new ArrayIndexOutOfBoundsException(); 2553 } 2554 if (bounds == null) { 2555 throw new NullPointerException("need bounds Rect"); 2556 } 2557 nGetCharArrayBounds(mNativePaint, mNativeTypeface, text, index, count, mBidiFlags, 2558 bounds); 2559 } 2560 2561 /** 2562 * Determine whether the typeface set on the paint has a glyph supporting the string. The 2563 * simplest case is when the string contains a single character, in which this method 2564 * determines whether the font has the character. In the case of multiple characters, the 2565 * method returns true if there is a single glyph representing the ligature. For example, if 2566 * the input is a pair of regional indicator symbols, determine whether there is an emoji flag 2567 * for the pair. 2568 * 2569 * <p>Finally, if the string contains a variation selector, the method only returns true if 2570 * the fonts contains a glyph specific to that variation. 2571 * 2572 * <p>Checking is done on the entire fallback chain, not just the immediate font referenced. 2573 * 2574 * @param string the string to test whether there is glyph support 2575 * @return true if the typeface has a glyph for the string 2576 */ 2577 public boolean hasGlyph(String string) { 2578 return nHasGlyph(mNativePaint, mNativeTypeface, mBidiFlags, string); 2579 } 2580 2581 /** 2582 * Measure cursor position within a run of text. 2583 * 2584 * <p>The run of text includes the characters from {@code start} to {@code end} in the text. In 2585 * addition, the range {@code contextStart} to {@code contextEnd} is used as context for the 2586 * purpose of complex text shaping, such as Arabic text potentially shaped differently based on 2587 * the text next to it. 2588 * 2589 * <p>All text outside the range {@code contextStart..contextEnd} is ignored. The text between 2590 * {@code start} and {@code end} will be laid out to be measured. 2591 * 2592 * <p>The returned width measurement is the advance from {@code start} to {@code offset}. It is 2593 * generally a positive value, no matter the direction of the run. If {@code offset == end}, 2594 * the return value is simply the width of the whole run from {@code start} to {@code end}. 2595 * 2596 * <p>Ligatures are formed for characters in the range {@code start..end} (but not for 2597 * {@code start..contextStart} or {@code end..contextEnd}). If {@code offset} points to a 2598 * character in the middle of such a formed ligature, but at a grapheme cluster boundary, the 2599 * return value will also reflect an advance in the middle of the ligature. See 2600 * {@link #getOffsetForAdvance} for more discussion of grapheme cluster boundaries. 2601 * 2602 * <p>The direction of the run is explicitly specified by {@code isRtl}. Thus, this method is 2603 * suitable only for runs of a single direction. 2604 * 2605 * <p>All indices are relative to the start of {@code text}. Further, {@code 0 <= contextStart 2606 * <= start <= offset <= end <= contextEnd <= text.length} must hold on entry. 2607 * 2608 * @param text the text to measure. Cannot be null. 2609 * @param start the index of the start of the range to measure 2610 * @param end the index + 1 of the end of the range to measure 2611 * @param contextStart the index of the start of the shaping context 2612 * @param contextEnd the index + 1 of the end of the shaping context 2613 * @param isRtl whether the run is in RTL direction 2614 * @param offset index of caret position 2615 * @return width measurement between start and offset 2616 */ 2617 public float getRunAdvance(char[] text, int start, int end, int contextStart, int contextEnd, 2618 boolean isRtl, int offset) { 2619 if (text == null) { 2620 throw new IllegalArgumentException("text cannot be null"); 2621 } 2622 if ((contextStart | start | offset | end | contextEnd 2623 | start - contextStart | offset - start | end - offset 2624 | contextEnd - end | text.length - contextEnd) < 0) { 2625 throw new IndexOutOfBoundsException(); 2626 } 2627 if (end == start) { 2628 return 0.0f; 2629 } 2630 // TODO: take mCompatScaling into account (or eliminate compat scaling)? 2631 return nGetRunAdvance(mNativePaint, mNativeTypeface, text, start, end, 2632 contextStart, contextEnd, isRtl, offset); 2633 } 2634 2635 /** 2636 * @see #getRunAdvance(char[], int, int, int, int, boolean, int) 2637 * 2638 * @param text the text to measure. Cannot be null. 2639 * @param start the index of the start of the range to measure 2640 * @param end the index + 1 of the end of the range to measure 2641 * @param contextStart the index of the start of the shaping context 2642 * @param contextEnd the index + 1 of the end of the shaping context 2643 * @param isRtl whether the run is in RTL direction 2644 * @param offset index of caret position 2645 * @return width measurement between start and offset 2646 */ 2647 public float getRunAdvance(CharSequence text, int start, int end, int contextStart, 2648 int contextEnd, boolean isRtl, int offset) { 2649 if (text == null) { 2650 throw new IllegalArgumentException("text cannot be null"); 2651 } 2652 if ((contextStart | start | offset | end | contextEnd 2653 | start - contextStart | offset - start | end - offset 2654 | contextEnd - end | text.length() - contextEnd) < 0) { 2655 throw new IndexOutOfBoundsException(); 2656 } 2657 if (end == start) { 2658 return 0.0f; 2659 } 2660 // TODO performance: specialized alternatives to avoid buffer copy, if win is significant 2661 char[] buf = TemporaryBuffer.obtain(contextEnd - contextStart); 2662 TextUtils.getChars(text, contextStart, contextEnd, buf, 0); 2663 float result = getRunAdvance(buf, start - contextStart, end - contextStart, 0, 2664 contextEnd - contextStart, isRtl, offset - contextStart); 2665 TemporaryBuffer.recycle(buf); 2666 return result; 2667 } 2668 2669 /** 2670 * Get the character offset within the string whose position is closest to the specified 2671 * horizontal position. 2672 * 2673 * <p>The returned value is generally the value of {@code offset} for which 2674 * {@link #getRunAdvance} yields a result most closely approximating {@code advance}, 2675 * and which is also on a grapheme cluster boundary. As such, it is the preferred method 2676 * for positioning a cursor in response to a touch or pointer event. The grapheme cluster 2677 * boundaries are based on 2678 * <a href="http://unicode.org/reports/tr29/">Unicode Standard Annex #29</a> but with some 2679 * tailoring for better user experience. 2680 * 2681 * <p>Note that {@code advance} is a (generally positive) width measurement relative to the start 2682 * of the run. Thus, for RTL runs it the distance from the point to the right edge. 2683 * 2684 * <p>All indices are relative to the start of {@code text}. Further, {@code 0 <= contextStart 2685 * <= start <= end <= contextEnd <= text.length} must hold on entry, and {@code start <= result 2686 * <= end} will hold on return. 2687 * 2688 * @param text the text to measure. Cannot be null. 2689 * @param start the index of the start of the range to measure 2690 * @param end the index + 1 of the end of the range to measure 2691 * @param contextStart the index of the start of the shaping context 2692 * @param contextEnd the index + 1 of the end of the range to measure 2693 * @param isRtl whether the run is in RTL direction 2694 * @param advance width relative to start of run 2695 * @return index of offset 2696 */ 2697 public int getOffsetForAdvance(char[] text, int start, int end, int contextStart, 2698 int contextEnd, boolean isRtl, float advance) { 2699 if (text == null) { 2700 throw new IllegalArgumentException("text cannot be null"); 2701 } 2702 if ((contextStart | start | end | contextEnd 2703 | start - contextStart | end - start | contextEnd - end 2704 | text.length - contextEnd) < 0) { 2705 throw new IndexOutOfBoundsException(); 2706 } 2707 // TODO: take mCompatScaling into account (or eliminate compat scaling)? 2708 return nGetOffsetForAdvance(mNativePaint, mNativeTypeface, text, start, end, 2709 contextStart, contextEnd, isRtl, advance); 2710 } 2711 2712 /** 2713 * @see #getOffsetForAdvance(char[], int, int, int, int, boolean, float) 2714 * 2715 * @param text the text to measure. Cannot be null. 2716 * @param start the index of the start of the range to measure 2717 * @param end the index + 1 of the end of the range to measure 2718 * @param contextStart the index of the start of the shaping context 2719 * @param contextEnd the index + 1 of the end of the range to measure 2720 * @param isRtl whether the run is in RTL direction 2721 * @param advance width relative to start of run 2722 * @return index of offset 2723 */ 2724 public int getOffsetForAdvance(CharSequence text, int start, int end, int contextStart, 2725 int contextEnd, boolean isRtl, float advance) { 2726 if (text == null) { 2727 throw new IllegalArgumentException("text cannot be null"); 2728 } 2729 if ((contextStart | start | end | contextEnd 2730 | start - contextStart | end - start | contextEnd - end 2731 | text.length() - contextEnd) < 0) { 2732 throw new IndexOutOfBoundsException(); 2733 } 2734 // TODO performance: specialized alternatives to avoid buffer copy, if win is significant 2735 char[] buf = TemporaryBuffer.obtain(contextEnd - contextStart); 2736 TextUtils.getChars(text, contextStart, contextEnd, buf, 0); 2737 int result = getOffsetForAdvance(buf, start - contextStart, end - contextStart, 0, 2738 contextEnd - contextStart, isRtl, advance) + contextStart; 2739 TemporaryBuffer.recycle(buf); 2740 return result; 2741 } 2742 2743 // regular JNI 2744 private static native long nGetNativeFinalizer(); 2745 private static native long nInit(); 2746 private static native long nInitWithPaint(long paint); 2747 private static native int nBreakText(long nObject, long nTypeface, 2748 char[] text, int index, int count, 2749 float maxWidth, int bidiFlags, float[] measuredWidth); 2750 private static native int nBreakText(long nObject, long nTypeface, 2751 String text, boolean measureForwards, 2752 float maxWidth, int bidiFlags, float[] measuredWidth); 2753 private static native float nGetTextAdvances(long paintPtr, long typefacePtr, 2754 char[] text, int index, int count, int contextIndex, int contextCount, 2755 int bidiFlags, float[] advances, int advancesIndex); 2756 private static native float nGetTextAdvances(long paintPtr, long typefacePtr, 2757 String text, int start, int end, int contextStart, int contextEnd, 2758 int bidiFlags, float[] advances, int advancesIndex); 2759 private native int nGetTextRunCursor(long paintPtr, long typefacePtr, char[] text, 2760 int contextStart, int contextLength, int dir, int offset, int cursorOpt); 2761 private native int nGetTextRunCursor(long paintPtr, long typefacePtr, String text, 2762 int contextStart, int contextEnd, int dir, int offset, int cursorOpt); 2763 private static native void nGetTextPath(long paintPtr, long typefacePtr, 2764 int bidiFlags, char[] text, int index, int count, float x, float y, long path); 2765 private static native void nGetTextPath(long paintPtr, long typefacePtr, 2766 int bidiFlags, String text, int start, int end, float x, float y, long path); 2767 private static native void nGetStringBounds(long nativePaint, long typefacePtr, 2768 String text, int start, int end, int bidiFlags, Rect bounds); 2769 private static native void nGetCharArrayBounds(long nativePaint, long typefacePtr, 2770 char[] text, int index, int count, int bidiFlags, Rect bounds); 2771 private static native boolean nHasGlyph(long paintPtr, long typefacePtr, 2772 int bidiFlags, String string); 2773 private static native float nGetRunAdvance(long paintPtr, long typefacePtr, 2774 char[] text, int start, int end, int contextStart, int contextEnd, boolean isRtl, 2775 int offset); 2776 private static native int nGetOffsetForAdvance(long paintPtr, 2777 long typefacePtr, char[] text, int start, int end, int contextStart, int contextEnd, 2778 boolean isRtl, float advance); 2779 2780 2781 // ---------------- @FastNative ------------------------ 2782 2783 @FastNative 2784 private static native int nSetTextLocales(long paintPtr, String locales); 2785 @FastNative 2786 private static native void nSetFontFeatureSettings(long paintPtr, String settings); 2787 @FastNative 2788 private static native float nGetFontMetrics(long paintPtr, 2789 long typefacePtr, FontMetrics metrics); 2790 @FastNative 2791 private static native int nGetFontMetricsInt(long paintPtr, 2792 long typefacePtr, FontMetricsInt fmi); 2793 2794 2795 // ---------------- @CriticalNative ------------------------ 2796 2797 @CriticalNative 2798 private static native void nReset(long paintPtr); 2799 @CriticalNative 2800 private static native void nSet(long paintPtrDest, long paintPtrSrc); 2801 @CriticalNative 2802 private static native int nGetStyle(long paintPtr); 2803 @CriticalNative 2804 private static native void nSetStyle(long paintPtr, int style); 2805 @CriticalNative 2806 private static native int nGetStrokeCap(long paintPtr); 2807 @CriticalNative 2808 private static native void nSetStrokeCap(long paintPtr, int cap); 2809 @CriticalNative 2810 private static native int nGetStrokeJoin(long paintPtr); 2811 @CriticalNative 2812 private static native void nSetStrokeJoin(long paintPtr, int join); 2813 @CriticalNative 2814 private static native boolean nGetFillPath(long paintPtr, long src, long dst); 2815 @CriticalNative 2816 private static native long nSetShader(long paintPtr, long shader); 2817 @CriticalNative 2818 private static native long nSetColorFilter(long paintPtr, long filter); 2819 @CriticalNative 2820 private static native void nSetXfermode(long paintPtr, int xfermode); 2821 @CriticalNative 2822 private static native long nSetPathEffect(long paintPtr, long effect); 2823 @CriticalNative 2824 private static native long nSetMaskFilter(long paintPtr, long maskfilter); 2825 @CriticalNative 2826 private static native long nSetTypeface(long paintPtr, long typeface); 2827 @CriticalNative 2828 private static native int nGetTextAlign(long paintPtr); 2829 @CriticalNative 2830 private static native void nSetTextAlign(long paintPtr, int align); 2831 @CriticalNative 2832 private static native void nSetTextLocalesByMinikinLangListId(long paintPtr, 2833 int mMinikinLangListId); 2834 @CriticalNative 2835 private static native void nSetShadowLayer(long paintPtr, 2836 float radius, float dx, float dy, int color); 2837 @CriticalNative 2838 private static native boolean nHasShadowLayer(long paintPtr); 2839 @CriticalNative 2840 private static native float nGetLetterSpacing(long paintPtr); 2841 @CriticalNative 2842 private static native void nSetLetterSpacing(long paintPtr, float letterSpacing); 2843 @CriticalNative 2844 private static native float nGetWordSpacing(long paintPtr); 2845 @CriticalNative 2846 private static native void nSetWordSpacing(long paintPtr, float wordSpacing); 2847 @CriticalNative 2848 private static native int nGetHyphenEdit(long paintPtr); 2849 @CriticalNative 2850 private static native void nSetHyphenEdit(long paintPtr, int hyphen); 2851 @CriticalNative 2852 private static native void nSetStrokeMiter(long paintPtr, float miter); 2853 @CriticalNative 2854 private static native float nGetStrokeMiter(long paintPtr); 2855 @CriticalNative 2856 private static native void nSetStrokeWidth(long paintPtr, float width); 2857 @CriticalNative 2858 private static native float nGetStrokeWidth(long paintPtr); 2859 @CriticalNative 2860 private static native void nSetAlpha(long paintPtr, int a); 2861 @CriticalNative 2862 private static native void nSetDither(long paintPtr, boolean dither); 2863 @CriticalNative 2864 private static native int nGetFlags(long paintPtr); 2865 @CriticalNative 2866 private static native void nSetFlags(long paintPtr, int flags); 2867 @CriticalNative 2868 private static native int nGetHinting(long paintPtr); 2869 @CriticalNative 2870 private static native void nSetHinting(long paintPtr, int mode); 2871 @CriticalNative 2872 private static native void nSetAntiAlias(long paintPtr, boolean aa); 2873 @CriticalNative 2874 private static native void nSetLinearText(long paintPtr, boolean linearText); 2875 @CriticalNative 2876 private static native void nSetSubpixelText(long paintPtr, boolean subpixelText); 2877 @CriticalNative 2878 private static native void nSetUnderlineText(long paintPtr, boolean underlineText); 2879 @CriticalNative 2880 private static native void nSetFakeBoldText(long paintPtr, boolean fakeBoldText); 2881 @CriticalNative 2882 private static native void nSetFilterBitmap(long paintPtr, boolean filter); 2883 @CriticalNative 2884 private static native int nGetColor(long paintPtr); 2885 @CriticalNative 2886 private static native void nSetColor(long paintPtr, @ColorInt int color); 2887 @CriticalNative 2888 private static native int nGetAlpha(long paintPtr); 2889 @CriticalNative 2890 private static native void nSetStrikeThruText(long paintPtr, boolean strikeThruText); 2891 @CriticalNative 2892 private static native boolean nIsElegantTextHeight(long paintPtr); 2893 @CriticalNative 2894 private static native void nSetElegantTextHeight(long paintPtr, boolean elegant); 2895 @CriticalNative 2896 private static native float nGetTextSize(long paintPtr); 2897 @CriticalNative 2898 private static native float nGetTextScaleX(long paintPtr); 2899 @CriticalNative 2900 private static native void nSetTextScaleX(long paintPtr, float scaleX); 2901 @CriticalNative 2902 private static native float nGetTextSkewX(long paintPtr); 2903 @CriticalNative 2904 private static native void nSetTextSkewX(long paintPtr, float skewX); 2905 @CriticalNative 2906 private static native float nAscent(long paintPtr, long typefacePtr); 2907 @CriticalNative 2908 private static native float nDescent(long paintPtr, long typefacePtr); 2909 @CriticalNative 2910 private static native void nSetTextSize(long paintPtr, float textSize); 2911} 2912