Paint.java revision 8e04840f38a16f806754dfca3de50c2548e67913
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.text.GraphicsOperations; 20import android.text.SpannableString; 21import android.text.SpannedString; 22import android.text.TextUtils; 23 24import java.util.Locale; 25 26/** 27 * The Paint class holds the style and color information about how to draw 28 * geometries, text and bitmaps. 29 */ 30public class Paint { 31 32 /** 33 * @hide 34 */ 35 public int mNativePaint; 36 37 private ColorFilter mColorFilter; 38 private MaskFilter mMaskFilter; 39 private PathEffect mPathEffect; 40 private Rasterizer mRasterizer; 41 private Shader mShader; 42 private Typeface mTypeface; 43 private Xfermode mXfermode; 44 45 private boolean mHasCompatScaling; 46 private float mCompatScaling; 47 private float mInvCompatScaling; 48 49 private Locale mLocale; 50 51 /** 52 * @hide 53 */ 54 public boolean hasShadow; 55 /** 56 * @hide 57 */ 58 public float shadowDx; 59 /** 60 * @hide 61 */ 62 public float shadowDy; 63 /** 64 * @hide 65 */ 66 public float shadowRadius; 67 /** 68 * @hide 69 */ 70 public int shadowColor; 71 72 static final Style[] sStyleArray = { 73 Style.FILL, Style.STROKE, Style.FILL_AND_STROKE 74 }; 75 static final Cap[] sCapArray = { 76 Cap.BUTT, Cap.ROUND, Cap.SQUARE 77 }; 78 static final Join[] sJoinArray = { 79 Join.MITER, Join.ROUND, Join.BEVEL 80 }; 81 static final Align[] sAlignArray = { 82 Align.LEFT, Align.CENTER, Align.RIGHT 83 }; 84 85 /** bit mask for the flag enabling antialiasing */ 86 public static final int ANTI_ALIAS_FLAG = 0x01; 87 /** bit mask for the flag enabling bitmap filtering */ 88 public static final int FILTER_BITMAP_FLAG = 0x02; 89 /** bit mask for the flag enabling dithering */ 90 public static final int DITHER_FLAG = 0x04; 91 /** bit mask for the flag enabling underline text */ 92 public static final int UNDERLINE_TEXT_FLAG = 0x08; 93 /** bit mask for the flag enabling strike-thru text */ 94 public static final int STRIKE_THRU_TEXT_FLAG = 0x10; 95 /** bit mask for the flag enabling fake-bold text */ 96 public static final int FAKE_BOLD_TEXT_FLAG = 0x20; 97 /** bit mask for the flag enabling linear-text (no caching) */ 98 public static final int LINEAR_TEXT_FLAG = 0x40; 99 /** bit mask for the flag enabling subpixel-text */ 100 public static final int SUBPIXEL_TEXT_FLAG = 0x80; 101 /** bit mask for the flag enabling device kerning for text */ 102 public static final int DEV_KERN_TEXT_FLAG = 0x100; 103 104 // we use this when we first create a paint 105 static final int DEFAULT_PAINT_FLAGS = DEV_KERN_TEXT_FLAG; 106 107 /** 108 * Option for {@link #setHinting}: disable hinting. 109 */ 110 public static final int HINTING_OFF = 0x0; 111 112 /** 113 * Option for {@link #setHinting}: enable hinting. 114 */ 115 public static final int HINTING_ON = 0x1; 116 117 /** 118 * Option for getTextRunCursor to compute the valid cursor after 119 * offset or the limit of the context, whichever is less. 120 * @hide 121 */ 122 public static final int CURSOR_AFTER = 0; 123 124 /** 125 * Option for getTextRunCursor to compute the valid cursor at or after 126 * the offset or the limit of the context, whichever is less. 127 * @hide 128 */ 129 public static final int CURSOR_AT_OR_AFTER = 1; 130 131 /** 132 * Option for getTextRunCursor to compute the valid cursor before 133 * offset or the start of the context, whichever is greater. 134 * @hide 135 */ 136 public static final int CURSOR_BEFORE = 2; 137 138 /** 139 * Option for getTextRunCursor to compute the valid cursor at or before 140 * offset or the start of the context, whichever is greater. 141 * @hide 142 */ 143 public static final int CURSOR_AT_OR_BEFORE = 3; 144 145 /** 146 * Option for getTextRunCursor to return offset if the cursor at offset 147 * is valid, or -1 if it isn't. 148 * @hide 149 */ 150 public static final int CURSOR_AT = 4; 151 152 /** 153 * Maximum cursor option value. 154 */ 155 private static final int CURSOR_OPT_MAX_VALUE = CURSOR_AT; 156 157 /** 158 * The Style specifies if the primitive being drawn is filled, stroked, or 159 * both (in the same color). The default is FILL. 160 */ 161 public enum Style { 162 /** 163 * Geometry and text drawn with this style will be filled, ignoring all 164 * stroke-related settings in the paint. 165 */ 166 FILL (0), 167 /** 168 * Geometry and text drawn with this style will be stroked, respecting 169 * the stroke-related fields on the paint. 170 */ 171 STROKE (1), 172 /** 173 * Geometry and text drawn with this style will be both filled and 174 * stroked at the same time, respecting the stroke-related fields on 175 * the paint. This mode can give unexpected results if the geometry 176 * is oriented counter-clockwise. This restriction does not apply to 177 * either FILL or STROKE. 178 */ 179 FILL_AND_STROKE (2); 180 181 Style(int nativeInt) { 182 this.nativeInt = nativeInt; 183 } 184 final int nativeInt; 185 } 186 187 /** 188 * The Cap specifies the treatment for the beginning and ending of 189 * stroked lines and paths. The default is BUTT. 190 */ 191 public enum Cap { 192 /** 193 * The stroke ends with the path, and does not project beyond it. 194 */ 195 BUTT (0), 196 /** 197 * The stroke projects out as a semicircle, with the center at the 198 * end of the path. 199 */ 200 ROUND (1), 201 /** 202 * The stroke projects out as a square, with the center at the end 203 * of the path. 204 */ 205 SQUARE (2); 206 207 private Cap(int nativeInt) { 208 this.nativeInt = nativeInt; 209 } 210 final int nativeInt; 211 } 212 213 /** 214 * The Join specifies the treatment where lines and curve segments 215 * join on a stroked path. The default is MITER. 216 */ 217 public enum Join { 218 /** 219 * The outer edges of a join meet at a sharp angle 220 */ 221 MITER (0), 222 /** 223 * The outer edges of a join meet in a circular arc. 224 */ 225 ROUND (1), 226 /** 227 * The outer edges of a join meet with a straight line 228 */ 229 BEVEL (2); 230 231 private Join(int nativeInt) { 232 this.nativeInt = nativeInt; 233 } 234 final int nativeInt; 235 } 236 237 /** 238 * Align specifies how drawText aligns its text relative to the 239 * [x,y] coordinates. The default is LEFT. 240 */ 241 public enum Align { 242 /** 243 * The text is drawn to the right of the x,y origin 244 */ 245 LEFT (0), 246 /** 247 * The text is drawn centered horizontally on the x,y origin 248 */ 249 CENTER (1), 250 /** 251 * The text is drawn to the left of the x,y origin 252 */ 253 RIGHT (2); 254 255 private Align(int nativeInt) { 256 this.nativeInt = nativeInt; 257 } 258 final int nativeInt; 259 } 260 261 /** 262 * Create a new paint with default settings. 263 */ 264 public Paint() { 265 this(0); 266 } 267 268 /** 269 * Create a new paint with the specified flags. Use setFlags() to change 270 * these after the paint is created. 271 * 272 * @param flags initial flag bits, as if they were passed via setFlags(). 273 */ 274 public Paint(int flags) { 275 mNativePaint = native_init(); 276 setFlags(flags | DEFAULT_PAINT_FLAGS); 277 // TODO: Turning off hinting has undesirable side effects, we need to 278 // revisit hinting once we add support for subpixel positioning 279 // setHinting(DisplayMetrics.DENSITY_DEVICE >= DisplayMetrics.DENSITY_TV 280 // ? HINTING_OFF : HINTING_ON); 281 mCompatScaling = mInvCompatScaling = 1; 282 setTextLocale(Locale.getDefault()); 283 } 284 285 /** 286 * Create a new paint, initialized with the attributes in the specified 287 * paint parameter. 288 * 289 * @param paint Existing paint used to initialized the attributes of the 290 * new paint. 291 */ 292 public Paint(Paint paint) { 293 mNativePaint = native_initWithPaint(paint.mNativePaint); 294 setClassVariablesFrom(paint); 295 } 296 297 /** Restores the paint to its default settings. */ 298 public void reset() { 299 native_reset(mNativePaint); 300 setFlags(DEFAULT_PAINT_FLAGS); 301 302 // TODO: Turning off hinting has undesirable side effects, we need to 303 // revisit hinting once we add support for subpixel positioning 304 // setHinting(DisplayMetrics.DENSITY_DEVICE >= DisplayMetrics.DENSITY_TV 305 // ? HINTING_OFF : HINTING_ON); 306 307 mColorFilter = null; 308 mMaskFilter = null; 309 mPathEffect = null; 310 mRasterizer = null; 311 mShader = null; 312 mTypeface = null; 313 mXfermode = null; 314 315 mHasCompatScaling = false; 316 mCompatScaling = 1; 317 mInvCompatScaling = 1; 318 319 hasShadow = false; 320 shadowDx = 0; 321 shadowDy = 0; 322 shadowRadius = 0; 323 shadowColor = 0; 324 325 setTextLocale(Locale.getDefault()); 326 } 327 328 /** 329 * Copy the fields from src into this paint. This is equivalent to calling 330 * get() on all of the src fields, and calling the corresponding set() 331 * methods on this. 332 */ 333 public void set(Paint src) { 334 if (this != src) { 335 // copy over the native settings 336 native_set(mNativePaint, src.mNativePaint); 337 setClassVariablesFrom(src); 338 } 339 } 340 341 /** 342 * Set all class variables using current values from the given 343 * {@link Paint}. 344 */ 345 private void setClassVariablesFrom(Paint paint) { 346 mColorFilter = paint.mColorFilter; 347 mMaskFilter = paint.mMaskFilter; 348 mPathEffect = paint.mPathEffect; 349 mRasterizer = paint.mRasterizer; 350 mShader = paint.mShader; 351 mTypeface = paint.mTypeface; 352 mXfermode = paint.mXfermode; 353 354 mHasCompatScaling = paint.mHasCompatScaling; 355 mCompatScaling = paint.mCompatScaling; 356 mInvCompatScaling = paint.mInvCompatScaling; 357 358 hasShadow = paint.hasShadow; 359 shadowDx = paint.shadowDx; 360 shadowDy = paint.shadowDy; 361 shadowRadius = paint.shadowRadius; 362 shadowColor = paint.shadowColor; 363 364 mLocale = paint.mLocale; 365 } 366 367 /** @hide */ 368 public void setCompatibilityScaling(float factor) { 369 if (factor == 1.0) { 370 mHasCompatScaling = false; 371 mCompatScaling = mInvCompatScaling = 1.0f; 372 } else { 373 mHasCompatScaling = true; 374 mCompatScaling = factor; 375 mInvCompatScaling = 1.0f/factor; 376 } 377 } 378 379 /** 380 * Return the paint's flags. Use the Flag enum to test flag values. 381 * 382 * @return the paint's flags (see enums ending in _Flag for bit masks) 383 */ 384 public native int getFlags(); 385 386 /** 387 * Set the paint's flags. Use the Flag enum to specific flag values. 388 * 389 * @param flags The new flag bits for the paint 390 */ 391 public native void setFlags(int flags); 392 393 /** 394 * Return the paint's hinting mode. Returns either 395 * {@link #HINTING_OFF} or {@link #HINTING_ON}. 396 */ 397 public native int getHinting(); 398 399 /** 400 * Set the paint's hinting mode. May be either 401 * {@link #HINTING_OFF} or {@link #HINTING_ON}. 402 */ 403 public native void setHinting(int mode); 404 405 /** 406 * Helper for getFlags(), returning true if ANTI_ALIAS_FLAG bit is set 407 * AntiAliasing smooths out the edges of what is being drawn, but is has 408 * no impact on the interior of the shape. See setDither() and 409 * setFilterBitmap() to affect how colors are treated. 410 * 411 * @return true if the antialias bit is set in the paint's flags. 412 */ 413 public final boolean isAntiAlias() { 414 return (getFlags() & ANTI_ALIAS_FLAG) != 0; 415 } 416 417 /** 418 * Helper for setFlags(), setting or clearing the ANTI_ALIAS_FLAG bit 419 * AntiAliasing smooths out the edges of what is being drawn, but is has 420 * no impact on the interior of the shape. See setDither() and 421 * setFilterBitmap() to affect how colors are treated. 422 * 423 * @param aa true to set the antialias bit in the flags, false to clear it 424 */ 425 public native void setAntiAlias(boolean aa); 426 427 /** 428 * Helper for getFlags(), returning true if DITHER_FLAG bit is set 429 * Dithering affects how colors that are higher precision than the device 430 * are down-sampled. No dithering is generally faster, but higher precision 431 * colors are just truncated down (e.g. 8888 -> 565). Dithering tries to 432 * distribute the error inherent in this process, to reduce the visual 433 * artifacts. 434 * 435 * @return true if the dithering bit is set in the paint's flags. 436 */ 437 public final boolean isDither() { 438 return (getFlags() & DITHER_FLAG) != 0; 439 } 440 441 /** 442 * Helper for setFlags(), setting or clearing the DITHER_FLAG bit 443 * Dithering affects how colors that are higher precision than the device 444 * are down-sampled. No dithering is generally faster, but higher precision 445 * colors are just truncated down (e.g. 8888 -> 565). Dithering tries to 446 * distribute the error inherent in this process, to reduce the visual 447 * artifacts. 448 * 449 * @param dither true to set the dithering bit in flags, false to clear it 450 */ 451 public native void setDither(boolean dither); 452 453 /** 454 * Helper for getFlags(), returning true if LINEAR_TEXT_FLAG bit is set 455 * 456 * @return true if the lineartext bit is set in the paint's flags 457 */ 458 public final boolean isLinearText() { 459 return (getFlags() & LINEAR_TEXT_FLAG) != 0; 460 } 461 462 /** 463 * Helper for setFlags(), setting or clearing the LINEAR_TEXT_FLAG bit 464 * 465 * @param linearText true to set the linearText bit in the paint's flags, 466 * false to clear it. 467 */ 468 public native void setLinearText(boolean linearText); 469 470 /** 471 * Helper for getFlags(), returning true if SUBPIXEL_TEXT_FLAG bit is set 472 * 473 * @return true if the subpixel bit is set in the paint's flags 474 */ 475 public final boolean isSubpixelText() { 476 return (getFlags() & SUBPIXEL_TEXT_FLAG) != 0; 477 } 478 479 /** 480 * Helper for setFlags(), setting or clearing the SUBPIXEL_TEXT_FLAG bit 481 * 482 * @param subpixelText true to set the subpixelText bit in the paint's 483 * flags, false to clear it. 484 */ 485 public native void setSubpixelText(boolean subpixelText); 486 487 /** 488 * Helper for getFlags(), returning true if UNDERLINE_TEXT_FLAG bit is set 489 * 490 * @return true if the underlineText bit is set in the paint's flags. 491 */ 492 public final boolean isUnderlineText() { 493 return (getFlags() & UNDERLINE_TEXT_FLAG) != 0; 494 } 495 496 /** 497 * Helper for setFlags(), setting or clearing the UNDERLINE_TEXT_FLAG bit 498 * 499 * @param underlineText true to set the underlineText bit in the paint's 500 * flags, false to clear it. 501 */ 502 public native void setUnderlineText(boolean underlineText); 503 504 /** 505 * Helper for getFlags(), returning true if STRIKE_THRU_TEXT_FLAG bit is set 506 * 507 * @return true if the strikeThruText bit is set in the paint's flags. 508 */ 509 public final boolean isStrikeThruText() { 510 return (getFlags() & STRIKE_THRU_TEXT_FLAG) != 0; 511 } 512 513 /** 514 * Helper for setFlags(), setting or clearing the STRIKE_THRU_TEXT_FLAG bit 515 * 516 * @param strikeThruText true to set the strikeThruText bit in the paint's 517 * flags, false to clear it. 518 */ 519 public native void setStrikeThruText(boolean strikeThruText); 520 521 /** 522 * Helper for getFlags(), returning true if FAKE_BOLD_TEXT_FLAG bit is set 523 * 524 * @return true if the fakeBoldText bit is set in the paint's flags. 525 */ 526 public final boolean isFakeBoldText() { 527 return (getFlags() & FAKE_BOLD_TEXT_FLAG) != 0; 528 } 529 530 /** 531 * Helper for setFlags(), setting or clearing the FAKE_BOLD_TEXT_FLAG bit 532 * 533 * @param fakeBoldText true to set the fakeBoldText bit in the paint's 534 * flags, false to clear it. 535 */ 536 public native void setFakeBoldText(boolean fakeBoldText); 537 538 /** 539 * Whether or not the bitmap filter is activated. 540 * Filtering affects the sampling of bitmaps when they are transformed. 541 * Filtering does not affect how the colors in the bitmap are converted into 542 * device pixels. That is dependent on dithering and xfermodes. 543 * 544 * @see #setFilterBitmap(boolean) setFilterBitmap() 545 */ 546 public final boolean isFilterBitmap() { 547 return (getFlags() & FILTER_BITMAP_FLAG) != 0; 548 } 549 550 /** 551 * Helper for setFlags(), setting or clearing the FILTER_BITMAP_FLAG bit. 552 * Filtering affects the sampling of bitmaps when they are transformed. 553 * Filtering does not affect how the colors in the bitmap are converted into 554 * device pixels. That is dependent on dithering and xfermodes. 555 * 556 * @param filter true to set the FILTER_BITMAP_FLAG bit in the paint's 557 * flags, false to clear it. 558 */ 559 public native void setFilterBitmap(boolean filter); 560 561 /** 562 * Return the paint's style, used for controlling how primitives' 563 * geometries are interpreted (except for drawBitmap, which always assumes 564 * FILL_STYLE). 565 * 566 * @return the paint's style setting (Fill, Stroke, StrokeAndFill) 567 */ 568 public Style getStyle() { 569 return sStyleArray[native_getStyle(mNativePaint)]; 570 } 571 572 /** 573 * Set the paint's style, used for controlling how primitives' 574 * geometries are interpreted (except for drawBitmap, which always assumes 575 * Fill). 576 * 577 * @param style The new style to set in the paint 578 */ 579 public void setStyle(Style style) { 580 native_setStyle(mNativePaint, style.nativeInt); 581 } 582 583 /** 584 * Return the paint's color. Note that the color is a 32bit value 585 * containing alpha as well as r,g,b. This 32bit value is not premultiplied, 586 * meaning that its alpha can be any value, regardless of the values of 587 * r,g,b. See the Color class for more details. 588 * 589 * @return the paint's color (and alpha). 590 */ 591 public native int getColor(); 592 593 /** 594 * Set the paint's color. Note that the color is an int containing alpha 595 * as well as r,g,b. This 32bit value is not premultiplied, meaning that 596 * its alpha can be any value, regardless of the values of r,g,b. 597 * See the Color class for more details. 598 * 599 * @param color The new color (including alpha) to set in the paint. 600 */ 601 public native void setColor(int color); 602 603 /** 604 * Helper to getColor() that just returns the color's alpha value. This is 605 * the same as calling getColor() >>> 24. It always returns a value between 606 * 0 (completely transparent) and 255 (completely opaque). 607 * 608 * @return the alpha component of the paint's color. 609 */ 610 public native int getAlpha(); 611 612 /** 613 * Helper to setColor(), that only assigns the color's alpha value, 614 * leaving its r,g,b values unchanged. Results are undefined if the alpha 615 * value is outside of the range [0..255] 616 * 617 * @param a set the alpha component [0..255] of the paint's color. 618 */ 619 public native void setAlpha(int a); 620 621 /** 622 * Helper to setColor(), that takes a,r,g,b and constructs the color int 623 * 624 * @param a The new alpha component (0..255) of the paint's color. 625 * @param r The new red component (0..255) of the paint's color. 626 * @param g The new green component (0..255) of the paint's color. 627 * @param b The new blue component (0..255) of the paint's color. 628 */ 629 public void setARGB(int a, int r, int g, int b) { 630 setColor((a << 24) | (r << 16) | (g << 8) | b); 631 } 632 633 /** 634 * Return the width for stroking. 635 * <p /> 636 * A value of 0 strokes in hairline mode. 637 * Hairlines always draws a single pixel independent of the canva's matrix. 638 * 639 * @return the paint's stroke width, used whenever the paint's style is 640 * Stroke or StrokeAndFill. 641 */ 642 public native float getStrokeWidth(); 643 644 /** 645 * Set the width for stroking. 646 * Pass 0 to stroke in hairline mode. 647 * Hairlines always draws a single pixel independent of the canva's matrix. 648 * 649 * @param width set the paint's stroke width, used whenever the paint's 650 * style is Stroke or StrokeAndFill. 651 */ 652 public native void setStrokeWidth(float width); 653 654 /** 655 * Return the paint's stroke miter value. Used to control the behavior 656 * of miter joins when the joins angle is sharp. 657 * 658 * @return the paint's miter limit, used whenever the paint's style is 659 * Stroke or StrokeAndFill. 660 */ 661 public native float getStrokeMiter(); 662 663 /** 664 * Set the paint's stroke miter value. This is used to control the behavior 665 * of miter joins when the joins angle is sharp. This value must be >= 0. 666 * 667 * @param miter set the miter limit on the paint, used whenever the paint's 668 * style is Stroke or StrokeAndFill. 669 */ 670 public native void setStrokeMiter(float miter); 671 672 /** 673 * Return the paint's Cap, controlling how the start and end of stroked 674 * lines and paths are treated. 675 * 676 * @return the line cap style for the paint, used whenever the paint's 677 * style is Stroke or StrokeAndFill. 678 */ 679 public Cap getStrokeCap() { 680 return sCapArray[native_getStrokeCap(mNativePaint)]; 681 } 682 683 /** 684 * Set the paint's Cap. 685 * 686 * @param cap set the paint's line cap style, used whenever the paint's 687 * style is Stroke or StrokeAndFill. 688 */ 689 public void setStrokeCap(Cap cap) { 690 native_setStrokeCap(mNativePaint, cap.nativeInt); 691 } 692 693 /** 694 * Return the paint's stroke join type. 695 * 696 * @return the paint's Join. 697 */ 698 public Join getStrokeJoin() { 699 return sJoinArray[native_getStrokeJoin(mNativePaint)]; 700 } 701 702 /** 703 * Set the paint's Join. 704 * 705 * @param join set the paint's Join, used whenever the paint's style is 706 * Stroke or StrokeAndFill. 707 */ 708 public void setStrokeJoin(Join join) { 709 native_setStrokeJoin(mNativePaint, join.nativeInt); 710 } 711 712 /** 713 * Applies any/all effects (patheffect, stroking) to src, returning the 714 * result in dst. The result is that drawing src with this paint will be 715 * the same as drawing dst with a default paint (at least from the 716 * geometric perspective). 717 * 718 * @param src input path 719 * @param dst output path (may be the same as src) 720 * @return true if the path should be filled, or false if it should be 721 * drawn with a hairline (width == 0) 722 */ 723 public boolean getFillPath(Path src, Path dst) { 724 return native_getFillPath(mNativePaint, src.ni(), dst.ni()); 725 } 726 727 /** 728 * Get the paint's shader object. 729 * 730 * @return the paint's shader (or null) 731 */ 732 public Shader getShader() { 733 return mShader; 734 } 735 736 /** 737 * Set or clear the shader object. 738 * <p /> 739 * Pass null to clear any previous shader. 740 * As a convenience, the parameter passed is also returned. 741 * 742 * @param shader May be null. the new shader to be installed in the paint 743 * @return shader 744 */ 745 public Shader setShader(Shader shader) { 746 int shaderNative = 0; 747 if (shader != null) 748 shaderNative = shader.native_instance; 749 native_setShader(mNativePaint, shaderNative); 750 mShader = shader; 751 return shader; 752 } 753 754 /** 755 * Get the paint's colorfilter (maybe be null). 756 * 757 * @return the paint's colorfilter (maybe be null) 758 */ 759 public ColorFilter getColorFilter() { 760 return mColorFilter; 761 } 762 763 /** 764 * Set or clear the paint's colorfilter, returning the parameter. 765 * 766 * @param filter May be null. The new filter to be installed in the paint 767 * @return filter 768 */ 769 public ColorFilter setColorFilter(ColorFilter filter) { 770 int filterNative = 0; 771 if (filter != null) 772 filterNative = filter.native_instance; 773 native_setColorFilter(mNativePaint, filterNative); 774 mColorFilter = filter; 775 return filter; 776 } 777 778 /** 779 * Get the paint's xfermode object. 780 * 781 * @return the paint's xfermode (or null) 782 */ 783 public Xfermode getXfermode() { 784 return mXfermode; 785 } 786 787 /** 788 * Set or clear the xfermode object. 789 * <p /> 790 * Pass null to clear any previous xfermode. 791 * As a convenience, the parameter passed is also returned. 792 * 793 * @param xfermode May be null. The xfermode to be installed in the paint 794 * @return xfermode 795 */ 796 public Xfermode setXfermode(Xfermode xfermode) { 797 int xfermodeNative = 0; 798 if (xfermode != null) 799 xfermodeNative = xfermode.native_instance; 800 native_setXfermode(mNativePaint, xfermodeNative); 801 mXfermode = xfermode; 802 return xfermode; 803 } 804 805 /** 806 * Get the paint's patheffect object. 807 * 808 * @return the paint's patheffect (or null) 809 */ 810 public PathEffect getPathEffect() { 811 return mPathEffect; 812 } 813 814 /** 815 * Set or clear the patheffect object. 816 * <p /> 817 * Pass null to clear any previous patheffect. 818 * As a convenience, the parameter passed is also returned. 819 * 820 * @param effect May be null. The patheffect to be installed in the paint 821 * @return effect 822 */ 823 public PathEffect setPathEffect(PathEffect effect) { 824 int effectNative = 0; 825 if (effect != null) { 826 effectNative = effect.native_instance; 827 } 828 native_setPathEffect(mNativePaint, effectNative); 829 mPathEffect = effect; 830 return effect; 831 } 832 833 /** 834 * Get the paint's maskfilter object. 835 * 836 * @return the paint's maskfilter (or null) 837 */ 838 public MaskFilter getMaskFilter() { 839 return mMaskFilter; 840 } 841 842 /** 843 * Set or clear the maskfilter object. 844 * <p /> 845 * Pass null to clear any previous maskfilter. 846 * As a convenience, the parameter passed is also returned. 847 * 848 * @param maskfilter May be null. The maskfilter to be installed in the 849 * paint 850 * @return maskfilter 851 */ 852 public MaskFilter setMaskFilter(MaskFilter maskfilter) { 853 int maskfilterNative = 0; 854 if (maskfilter != null) { 855 maskfilterNative = maskfilter.native_instance; 856 } 857 native_setMaskFilter(mNativePaint, maskfilterNative); 858 mMaskFilter = maskfilter; 859 return maskfilter; 860 } 861 862 /** 863 * Get the paint's typeface object. 864 * <p /> 865 * The typeface object identifies which font to use when drawing or 866 * measuring text. 867 * 868 * @return the paint's typeface (or null) 869 */ 870 public Typeface getTypeface() { 871 return mTypeface; 872 } 873 874 /** 875 * Set or clear the typeface object. 876 * <p /> 877 * Pass null to clear any previous typeface. 878 * As a convenience, the parameter passed is also returned. 879 * 880 * @param typeface May be null. The typeface to be installed in the paint 881 * @return typeface 882 */ 883 public Typeface setTypeface(Typeface typeface) { 884 int typefaceNative = 0; 885 if (typeface != null) { 886 typefaceNative = typeface.native_instance; 887 } 888 native_setTypeface(mNativePaint, typefaceNative); 889 mTypeface = typeface; 890 return typeface; 891 } 892 893 /** 894 * Get the paint's rasterizer (or null). 895 * <p /> 896 * The raster controls/modifies how paths/text are turned into alpha masks. 897 * 898 * @return the paint's rasterizer (or null) 899 */ 900 public Rasterizer getRasterizer() { 901 return mRasterizer; 902 } 903 904 /** 905 * Set or clear the rasterizer object. 906 * <p /> 907 * Pass null to clear any previous rasterizer. 908 * As a convenience, the parameter passed is also returned. 909 * 910 * @param rasterizer May be null. The new rasterizer to be installed in 911 * the paint. 912 * @return rasterizer 913 */ 914 public Rasterizer setRasterizer(Rasterizer rasterizer) { 915 int rasterizerNative = 0; 916 if (rasterizer != null) { 917 rasterizerNative = rasterizer.native_instance; 918 } 919 native_setRasterizer(mNativePaint, rasterizerNative); 920 mRasterizer = rasterizer; 921 return rasterizer; 922 } 923 924 /** 925 * This draws a shadow layer below the main layer, with the specified 926 * offset and color, and blur radius. If radius is 0, then the shadow 927 * layer is removed. 928 */ 929 public void setShadowLayer(float radius, float dx, float dy, int color) { 930 hasShadow = radius > 0.0f; 931 shadowRadius = radius; 932 shadowDx = dx; 933 shadowDy = dy; 934 shadowColor = color; 935 nSetShadowLayer(radius, dx, dy, color); 936 } 937 938 private native void nSetShadowLayer(float radius, float dx, float dy, int color); 939 940 /** 941 * Clear the shadow layer. 942 */ 943 public void clearShadowLayer() { 944 hasShadow = false; 945 nSetShadowLayer(0, 0, 0, 0); 946 } 947 948 /** 949 * Return the paint's Align value for drawing text. This controls how the 950 * text is positioned relative to its origin. LEFT align means that all of 951 * the text will be drawn to the right of its origin (i.e. the origin 952 * specifieds the LEFT edge of the text) and so on. 953 * 954 * @return the paint's Align value for drawing text. 955 */ 956 public Align getTextAlign() { 957 return sAlignArray[native_getTextAlign(mNativePaint)]; 958 } 959 960 /** 961 * Set the paint's text alignment. This controls how the 962 * text is positioned relative to its origin. LEFT align means that all of 963 * the text will be drawn to the right of its origin (i.e. the origin 964 * specifieds the LEFT edge of the text) and so on. 965 * 966 * @param align set the paint's Align value for drawing text. 967 */ 968 public void setTextAlign(Align align) { 969 native_setTextAlign(mNativePaint, align.nativeInt); 970 } 971 972 /** 973 * Get the text Locale. 974 * 975 * @return the paint's Locale used for drawing text, never null. 976 */ 977 public Locale getTextLocale() { 978 return mLocale; 979 } 980 981 /** 982 * Set the text locale. 983 * 984 * The text locale affects how the text is drawn for some languages. 985 * 986 * For example, if the locale is {@link Locale#CHINESE} or {@link Locale#CHINA}, 987 * then the text renderer will prefer to draw text using a Chinese font. Likewise, 988 * if the locale is {@link Locale#JAPANESE} or {@link Locale#JAPAN}, then the text 989 * renderer will prefer to draw text using a Japanese font. 990 * 991 * This distinction is important because Chinese and Japanese text both use many 992 * of the same Unicode code points but their appearance is subtly different for 993 * each language. 994 * 995 * By default, the text locale is initialized to the system locale (as returned 996 * by {@link Locale#getDefault}). This assumes that the text to be rendered will 997 * most likely be in the user's preferred language. 998 * 999 * If the actual language of the text is known, then it can be provided to the 1000 * text renderer using this method. The text renderer may attempt to guess the 1001 * language script based on the contents of the text to be drawn independent of 1002 * the text locale here. Specifying the text locale just helps it do a better 1003 * job in certain ambiguous cases 1004 * 1005 * @param locale the paint's locale value for drawing text, must not be null. 1006 */ 1007 public void setTextLocale(Locale locale) { 1008 if (locale == null) { 1009 throw new IllegalArgumentException("locale cannot be null"); 1010 } 1011 if (locale.equals(mLocale)) return; 1012 mLocale = locale; 1013 native_setTextLocale(mNativePaint, locale.toString()); 1014 } 1015 1016 /** 1017 * Return the paint's text size. 1018 * 1019 * @return the paint's text size. 1020 */ 1021 public native float getTextSize(); 1022 1023 /** 1024 * Set the paint's text size. This value must be > 0 1025 * 1026 * @param textSize set the paint's text size. 1027 */ 1028 public native void setTextSize(float textSize); 1029 1030 /** 1031 * Return the paint's horizontal scale factor for text. The default value 1032 * is 1.0. 1033 * 1034 * @return the paint's scale factor in X for drawing/measuring text 1035 */ 1036 public native float getTextScaleX(); 1037 1038 /** 1039 * Set the paint's horizontal scale factor for text. The default value 1040 * is 1.0. Values > 1.0 will stretch the text wider. Values < 1.0 will 1041 * stretch the text narrower. 1042 * 1043 * @param scaleX set the paint's scale in X for drawing/measuring text. 1044 */ 1045 public native void setTextScaleX(float scaleX); 1046 1047 /** 1048 * Return the paint's horizontal skew factor for text. The default value 1049 * is 0. 1050 * 1051 * @return the paint's skew factor in X for drawing text. 1052 */ 1053 public native float getTextSkewX(); 1054 1055 /** 1056 * Set the paint's horizontal skew factor for text. The default value 1057 * is 0. For approximating oblique text, use values around -0.25. 1058 * 1059 * @param skewX set the paint's skew factor in X for drawing text. 1060 */ 1061 public native void setTextSkewX(float skewX); 1062 1063 /** 1064 * Return the distance above (negative) the baseline (ascent) based on the 1065 * current typeface and text size. 1066 * 1067 * @return the distance above (negative) the baseline (ascent) based on the 1068 * current typeface and text size. 1069 */ 1070 public native float ascent(); 1071 1072 /** 1073 * Return the distance below (positive) the baseline (descent) based on the 1074 * current typeface and text size. 1075 * 1076 * @return the distance below (positive) the baseline (descent) based on 1077 * the current typeface and text size. 1078 */ 1079 public native float descent(); 1080 1081 /** 1082 * Class that describes the various metrics for a font at a given text size. 1083 * Remember, Y values increase going down, so those values will be positive, 1084 * and values that measure distances going up will be negative. This class 1085 * is returned by getFontMetrics(). 1086 */ 1087 public static class FontMetrics { 1088 /** 1089 * The maximum distance above the baseline for the tallest glyph in 1090 * the font at a given text size. 1091 */ 1092 public float top; 1093 /** 1094 * The recommended distance above the baseline for singled spaced text. 1095 */ 1096 public float ascent; 1097 /** 1098 * The recommended distance below the baseline for singled spaced text. 1099 */ 1100 public float descent; 1101 /** 1102 * The maximum distance below the baseline for the lowest glyph in 1103 * the font at a given text size. 1104 */ 1105 public float bottom; 1106 /** 1107 * The recommended additional space to add between lines of text. 1108 */ 1109 public float leading; 1110 } 1111 1112 /** 1113 * Return the font's recommended interline spacing, given the Paint's 1114 * settings for typeface, textSize, etc. If metrics is not null, return the 1115 * fontmetric values in it. 1116 * 1117 * @param metrics If this object is not null, its fields are filled with 1118 * the appropriate values given the paint's text attributes. 1119 * @return the font's recommended interline spacing. 1120 */ 1121 public native float getFontMetrics(FontMetrics metrics); 1122 1123 /** 1124 * Allocates a new FontMetrics object, and then calls getFontMetrics(fm) 1125 * with it, returning the object. 1126 */ 1127 public FontMetrics getFontMetrics() { 1128 FontMetrics fm = new FontMetrics(); 1129 getFontMetrics(fm); 1130 return fm; 1131 } 1132 1133 /** 1134 * Convenience method for callers that want to have FontMetrics values as 1135 * integers. 1136 */ 1137 public static class FontMetricsInt { 1138 public int top; 1139 public int ascent; 1140 public int descent; 1141 public int bottom; 1142 public int leading; 1143 1144 @Override public String toString() { 1145 return "FontMetricsInt: top=" + top + " ascent=" + ascent + 1146 " descent=" + descent + " bottom=" + bottom + 1147 " leading=" + leading; 1148 } 1149 } 1150 1151 /** 1152 * Return the font's interline spacing, given the Paint's settings for 1153 * typeface, textSize, etc. If metrics is not null, return the fontmetric 1154 * values in it. Note: all values have been converted to integers from 1155 * floats, in such a way has to make the answers useful for both spacing 1156 * and clipping. If you want more control over the rounding, call 1157 * getFontMetrics(). 1158 * 1159 * @return the font's interline spacing. 1160 */ 1161 public native int getFontMetricsInt(FontMetricsInt fmi); 1162 1163 public FontMetricsInt getFontMetricsInt() { 1164 FontMetricsInt fm = new FontMetricsInt(); 1165 getFontMetricsInt(fm); 1166 return fm; 1167 } 1168 1169 /** 1170 * Return the recommend line spacing based on the current typeface and 1171 * text size. 1172 * 1173 * @return recommend line spacing based on the current typeface and 1174 * text size. 1175 */ 1176 public float getFontSpacing() { 1177 return getFontMetrics(null); 1178 } 1179 1180 /** 1181 * Return the width of the text. 1182 * 1183 * @param text The text to measure. Cannot be null. 1184 * @param index The index of the first character to start measuring 1185 * @param count THe number of characters to measure, beginning with start 1186 * @return The width of the text 1187 */ 1188 public float measureText(char[] text, int index, int count) { 1189 if (text == null) { 1190 throw new IllegalArgumentException("text cannot be null"); 1191 } 1192 if ((index | count) < 0 || index + count > text.length) { 1193 throw new ArrayIndexOutOfBoundsException(); 1194 } 1195 1196 if (text.length == 0 || count == 0) { 1197 return 0f; 1198 } 1199 if (!mHasCompatScaling) { 1200 return (float) Math.ceil(native_measureText(text, index, count)); 1201 } 1202 1203 final float oldSize = getTextSize(); 1204 setTextSize(oldSize*mCompatScaling); 1205 float w = native_measureText(text, index, count); 1206 setTextSize(oldSize); 1207 return (float) Math.ceil(w*mInvCompatScaling); 1208 } 1209 1210 private native float native_measureText(char[] text, int index, int count); 1211 1212 /** 1213 * Return the width of the text. 1214 * 1215 * @param text The text to measure. Cannot be null. 1216 * @param start The index of the first character to start measuring 1217 * @param end 1 beyond the index of the last character to measure 1218 * @return The width of the text 1219 */ 1220 public float measureText(String text, int start, int end) { 1221 if (text == null) { 1222 throw new IllegalArgumentException("text cannot be null"); 1223 } 1224 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1225 throw new IndexOutOfBoundsException(); 1226 } 1227 1228 if (text.length() == 0 || start == end) { 1229 return 0f; 1230 } 1231 if (!mHasCompatScaling) { 1232 return (float) Math.ceil(native_measureText(text, start, end)); 1233 } 1234 1235 final float oldSize = getTextSize(); 1236 setTextSize(oldSize*mCompatScaling); 1237 float w = native_measureText(text, start, end); 1238 setTextSize(oldSize); 1239 return (float) Math.ceil(w*mInvCompatScaling); 1240 } 1241 1242 private native float native_measureText(String text, int start, int end); 1243 1244 /** 1245 * Return the width of the text. 1246 * 1247 * @param text The text to measure. Cannot be null. 1248 * @return The width of the text 1249 */ 1250 public float measureText(String text) { 1251 if (text == null) { 1252 throw new IllegalArgumentException("text cannot be null"); 1253 } 1254 1255 if (text.length() == 0) { 1256 return 0f; 1257 } 1258 1259 if (!mHasCompatScaling) { 1260 return (float) Math.ceil(native_measureText(text)); 1261 } 1262 final float oldSize = getTextSize(); 1263 setTextSize(oldSize*mCompatScaling); 1264 float w = native_measureText(text); 1265 setTextSize(oldSize); 1266 return (float) Math.ceil(w*mInvCompatScaling); 1267 } 1268 1269 private native float native_measureText(String text); 1270 1271 /** 1272 * Return the width of the text. 1273 * 1274 * @param text The text to measure 1275 * @param start The index of the first character to start measuring 1276 * @param end 1 beyond the index of the last character to measure 1277 * @return The width of the text 1278 */ 1279 public float measureText(CharSequence text, int start, int end) { 1280 if (text == null) { 1281 throw new IllegalArgumentException("text cannot be null"); 1282 } 1283 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1284 throw new IndexOutOfBoundsException(); 1285 } 1286 1287 if (text.length() == 0 || start == end) { 1288 return 0f; 1289 } 1290 if (text instanceof String) { 1291 return measureText((String)text, start, end); 1292 } 1293 if (text instanceof SpannedString || 1294 text instanceof SpannableString) { 1295 return measureText(text.toString(), start, end); 1296 } 1297 if (text instanceof GraphicsOperations) { 1298 return ((GraphicsOperations)text).measureText(start, end, this); 1299 } 1300 1301 char[] buf = TemporaryBuffer.obtain(end - start); 1302 TextUtils.getChars(text, start, end, buf, 0); 1303 float result = measureText(buf, 0, end - start); 1304 TemporaryBuffer.recycle(buf); 1305 return result; 1306 } 1307 1308 /** 1309 * Measure the text, stopping early if the measured width exceeds maxWidth. 1310 * Return the number of chars that were measured, and if measuredWidth is 1311 * not null, return in it the actual width measured. 1312 * 1313 * @param text The text to measure. Cannot be null. 1314 * @param index The offset into text to begin measuring at 1315 * @param count The number of maximum number of entries to measure. If count 1316 * is negative, then the characters are measured in reverse order. 1317 * @param maxWidth The maximum width to accumulate. 1318 * @param measuredWidth Optional. If not null, returns the actual width 1319 * measured. 1320 * @return The number of chars that were measured. Will always be <= 1321 * abs(count). 1322 */ 1323 public int breakText(char[] text, int index, int count, 1324 float maxWidth, float[] measuredWidth) { 1325 if (text == null) { 1326 throw new IllegalArgumentException("text cannot be null"); 1327 } 1328 if (index < 0 || text.length - index < Math.abs(count)) { 1329 throw new ArrayIndexOutOfBoundsException(); 1330 } 1331 1332 if (text.length == 0 || count == 0) { 1333 return 0; 1334 } 1335 if (!mHasCompatScaling) { 1336 return native_breakText(text, index, count, maxWidth, measuredWidth); 1337 } 1338 1339 final float oldSize = getTextSize(); 1340 setTextSize(oldSize*mCompatScaling); 1341 int res = native_breakText(text, index, count, maxWidth*mCompatScaling, 1342 measuredWidth); 1343 setTextSize(oldSize); 1344 if (measuredWidth != null) measuredWidth[0] *= mInvCompatScaling; 1345 return res; 1346 } 1347 1348 private native int native_breakText(char[] text, int index, int count, 1349 float maxWidth, float[] measuredWidth); 1350 1351 /** 1352 * Measure the text, stopping early if the measured width exceeds maxWidth. 1353 * Return the number of chars that were measured, and if measuredWidth is 1354 * not null, return in it the actual width measured. 1355 * 1356 * @param text The text to measure. Cannot be null. 1357 * @param start The offset into text to begin measuring at 1358 * @param end The end of the text slice to measure. 1359 * @param measureForwards If true, measure forwards, starting at start. 1360 * Otherwise, measure backwards, starting with end. 1361 * @param maxWidth The maximum width to accumulate. 1362 * @param measuredWidth Optional. If not null, returns the actual width 1363 * measured. 1364 * @return The number of chars that were measured. Will always be <= 1365 * abs(end - start). 1366 */ 1367 public int breakText(CharSequence text, int start, int end, 1368 boolean measureForwards, 1369 float maxWidth, float[] measuredWidth) { 1370 if (text == null) { 1371 throw new IllegalArgumentException("text cannot be null"); 1372 } 1373 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1374 throw new IndexOutOfBoundsException(); 1375 } 1376 1377 if (text.length() == 0 || start == end) { 1378 return 0; 1379 } 1380 if (start == 0 && text instanceof String && end == text.length()) { 1381 return breakText((String) text, measureForwards, maxWidth, 1382 measuredWidth); 1383 } 1384 1385 char[] buf = TemporaryBuffer.obtain(end - start); 1386 int result; 1387 1388 TextUtils.getChars(text, start, end, buf, 0); 1389 1390 if (measureForwards) { 1391 result = breakText(buf, 0, end - start, maxWidth, measuredWidth); 1392 } else { 1393 result = breakText(buf, 0, -(end - start), maxWidth, measuredWidth); 1394 } 1395 1396 TemporaryBuffer.recycle(buf); 1397 return result; 1398 } 1399 1400 /** 1401 * Measure the text, stopping early if the measured width exceeds maxWidth. 1402 * Return the number of chars that were measured, and if measuredWidth is 1403 * not null, return in it the actual width measured. 1404 * 1405 * @param text The text to measure. Cannot be null. 1406 * @param measureForwards If true, measure forwards, starting with the 1407 * first character in the string. Otherwise, 1408 * measure backwards, starting with the 1409 * last character in the string. 1410 * @param maxWidth The maximum width to accumulate. 1411 * @param measuredWidth Optional. If not null, returns the actual width 1412 * measured. 1413 * @return The number of chars that were measured. Will always be <= 1414 * abs(count). 1415 */ 1416 public int breakText(String text, boolean measureForwards, 1417 float maxWidth, float[] measuredWidth) { 1418 if (text == null) { 1419 throw new IllegalArgumentException("text cannot be null"); 1420 } 1421 1422 if (text.length() == 0) { 1423 return 0; 1424 } 1425 if (!mHasCompatScaling) { 1426 return native_breakText(text, measureForwards, maxWidth, measuredWidth); 1427 } 1428 1429 final float oldSize = getTextSize(); 1430 setTextSize(oldSize*mCompatScaling); 1431 int res = native_breakText(text, measureForwards, maxWidth*mCompatScaling, 1432 measuredWidth); 1433 setTextSize(oldSize); 1434 if (measuredWidth != null) measuredWidth[0] *= mInvCompatScaling; 1435 return res; 1436 } 1437 1438 private native int native_breakText(String text, boolean measureForwards, 1439 float maxWidth, float[] measuredWidth); 1440 1441 /** 1442 * Return the advance widths for the characters in the string. 1443 * 1444 * @param text The text to measure. Cannot be null. 1445 * @param index The index of the first char to to measure 1446 * @param count The number of chars starting with index to measure 1447 * @param widths array to receive the advance widths of the characters. 1448 * Must be at least a large as count. 1449 * @return the actual number of widths returned. 1450 */ 1451 public int getTextWidths(char[] text, int index, int count, 1452 float[] widths) { 1453 if (text == null) { 1454 throw new IllegalArgumentException("text cannot be null"); 1455 } 1456 if ((index | count) < 0 || index + count > text.length 1457 || count > widths.length) { 1458 throw new ArrayIndexOutOfBoundsException(); 1459 } 1460 1461 if (text.length == 0 || count == 0) { 1462 return 0; 1463 } 1464 if (!mHasCompatScaling) { 1465 return native_getTextWidths(mNativePaint, text, index, count, widths); 1466 } 1467 1468 final float oldSize = getTextSize(); 1469 setTextSize(oldSize*mCompatScaling); 1470 int res = native_getTextWidths(mNativePaint, text, index, count, widths); 1471 setTextSize(oldSize); 1472 for (int i=0; i<res; i++) { 1473 widths[i] *= mInvCompatScaling; 1474 } 1475 return res; 1476 } 1477 1478 /** 1479 * Return the advance widths for the characters in the string. 1480 * 1481 * @param text The text to measure. Cannot be null. 1482 * @param start The index of the first char to to measure 1483 * @param end The end of the text slice to measure 1484 * @param widths array to receive the advance widths of the characters. 1485 * Must be at least a large as (end - start). 1486 * @return the actual number of widths returned. 1487 */ 1488 public int getTextWidths(CharSequence text, int start, int end, 1489 float[] widths) { 1490 if (text == null) { 1491 throw new IllegalArgumentException("text cannot be null"); 1492 } 1493 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1494 throw new IndexOutOfBoundsException(); 1495 } 1496 if (end - start > widths.length) { 1497 throw new ArrayIndexOutOfBoundsException(); 1498 } 1499 1500 if (text.length() == 0 || start == end) { 1501 return 0; 1502 } 1503 if (text instanceof String) { 1504 return getTextWidths((String) text, start, end, widths); 1505 } 1506 if (text instanceof SpannedString || 1507 text instanceof SpannableString) { 1508 return getTextWidths(text.toString(), start, end, widths); 1509 } 1510 if (text instanceof GraphicsOperations) { 1511 return ((GraphicsOperations) text).getTextWidths(start, end, 1512 widths, this); 1513 } 1514 1515 char[] buf = TemporaryBuffer.obtain(end - start); 1516 TextUtils.getChars(text, start, end, buf, 0); 1517 int result = getTextWidths(buf, 0, end - start, widths); 1518 TemporaryBuffer.recycle(buf); 1519 return result; 1520 } 1521 1522 /** 1523 * Return the advance widths for the characters in the string. 1524 * 1525 * @param text The text to measure. Cannot be null. 1526 * @param start The index of the first char to to measure 1527 * @param end The end of the text slice to measure 1528 * @param widths array to receive the advance widths of the characters. 1529 * Must be at least a large as the text. 1530 * @return the number of unichars in the specified text. 1531 */ 1532 public int getTextWidths(String text, int start, int end, float[] widths) { 1533 if (text == null) { 1534 throw new IllegalArgumentException("text cannot be null"); 1535 } 1536 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1537 throw new IndexOutOfBoundsException(); 1538 } 1539 if (end - start > widths.length) { 1540 throw new ArrayIndexOutOfBoundsException(); 1541 } 1542 1543 if (text.length() == 0 || start == end) { 1544 return 0; 1545 } 1546 if (!mHasCompatScaling) { 1547 return native_getTextWidths(mNativePaint, text, start, end, widths); 1548 } 1549 1550 final float oldSize = getTextSize(); 1551 setTextSize(oldSize*mCompatScaling); 1552 int res = native_getTextWidths(mNativePaint, text, start, end, widths); 1553 setTextSize(oldSize); 1554 for (int i=0; i<res; i++) { 1555 widths[i] *= mInvCompatScaling; 1556 } 1557 return res; 1558 } 1559 1560 /** 1561 * Return the advance widths for the characters in the string. 1562 * 1563 * @param text The text to measure 1564 * @param widths array to receive the advance widths of the characters. 1565 * Must be at least a large as the text. 1566 * @return the number of unichars in the specified text. 1567 */ 1568 public int getTextWidths(String text, float[] widths) { 1569 return getTextWidths(text, 0, text.length(), widths); 1570 } 1571 1572 /** 1573 * Convenience overload that takes a char array instead of a 1574 * String. 1575 * 1576 * @see #getTextRunAdvances(String, int, int, int, int, float[], int) 1577 * @hide 1578 */ 1579 public float getTextRunAdvances(char[] chars, int index, int count, 1580 int contextIndex, int contextCount, float[] advances, 1581 int advancesIndex) { 1582 1583 if (chars == null) { 1584 throw new IllegalArgumentException("text cannot be null"); 1585 } 1586 if ((index | count | contextIndex | contextCount | advancesIndex 1587 | (index - contextIndex) | (contextCount - count) 1588 | ((contextIndex + contextCount) - (index + count)) 1589 | (chars.length - (contextIndex + contextCount)) 1590 | (advances == null ? 0 : 1591 (advances.length - (advancesIndex + count)))) < 0) { 1592 throw new IndexOutOfBoundsException(); 1593 } 1594 1595 if (chars.length == 0 || count == 0){ 1596 return 0f; 1597 } 1598 if (!mHasCompatScaling) { 1599 return native_getTextRunAdvances(mNativePaint, chars, index, count, 1600 contextIndex, contextCount, advances, advancesIndex); 1601 } 1602 1603 final float oldSize = getTextSize(); 1604 setTextSize(oldSize * mCompatScaling); 1605 float res = native_getTextRunAdvances(mNativePaint, chars, index, count, 1606 contextIndex, contextCount, advances, advancesIndex); 1607 setTextSize(oldSize); 1608 1609 if (advances != null) { 1610 for (int i = advancesIndex, e = i + count; i < e; i++) { 1611 advances[i] *= mInvCompatScaling; 1612 } 1613 } 1614 return res * mInvCompatScaling; // assume errors are not significant 1615 } 1616 1617 /** 1618 * Convenience overload that takes a CharSequence instead of a 1619 * String. 1620 * 1621 * @see #getTextRunAdvances(String, int, int, int, int, float[], int) 1622 * @hide 1623 */ 1624 public float getTextRunAdvances(CharSequence text, int start, int end, 1625 int contextStart, int contextEnd, float[] advances, 1626 int advancesIndex) { 1627 1628 if (text == null) { 1629 throw new IllegalArgumentException("text cannot be null"); 1630 } 1631 if ((start | end | contextStart | contextEnd | advancesIndex | (end - start) 1632 | (start - contextStart) | (contextEnd - end) 1633 | (text.length() - contextEnd) 1634 | (advances == null ? 0 : 1635 (advances.length - advancesIndex - (end - start)))) < 0) { 1636 throw new IndexOutOfBoundsException(); 1637 } 1638 1639 if (text instanceof String) { 1640 return getTextRunAdvances((String) text, start, end, 1641 contextStart, contextEnd, advances, advancesIndex); 1642 } 1643 if (text instanceof SpannedString || 1644 text instanceof SpannableString) { 1645 return getTextRunAdvances(text.toString(), start, end, 1646 contextStart, contextEnd, advances, advancesIndex); 1647 } 1648 if (text instanceof GraphicsOperations) { 1649 return ((GraphicsOperations) text).getTextRunAdvances(start, end, 1650 contextStart, contextEnd, advances, advancesIndex, this); 1651 } 1652 if (text.length() == 0 || end == start) { 1653 return 0f; 1654 } 1655 1656 int contextLen = contextEnd - contextStart; 1657 int len = end - start; 1658 char[] buf = TemporaryBuffer.obtain(contextLen); 1659 TextUtils.getChars(text, contextStart, contextEnd, buf, 0); 1660 float result = getTextRunAdvances(buf, start - contextStart, len, 1661 0, contextLen, advances, advancesIndex); 1662 TemporaryBuffer.recycle(buf); 1663 return result; 1664 } 1665 1666 /** 1667 * Returns the total advance width for the characters in the run 1668 * between start and end, and if advances is not null, the advance 1669 * assigned to each of these characters (java chars). 1670 * 1671 * <p>The trailing surrogate in a valid surrogate pair is assigned 1672 * an advance of 0. Thus the number of returned advances is 1673 * always equal to count, not to the number of unicode codepoints 1674 * represented by the run. 1675 * 1676 * <p>In the case of conjuncts or combining marks, the total 1677 * advance is assigned to the first logical character, and the 1678 * following characters are assigned an advance of 0. 1679 * 1680 * <p>This generates the sum of the advances of glyphs for 1681 * characters in a reordered cluster as the width of the first 1682 * logical character in the cluster, and 0 for the widths of all 1683 * other characters in the cluster. In effect, such clusters are 1684 * treated like conjuncts. 1685 * 1686 * <p>The shaping bounds limit the amount of context available 1687 * outside start and end that can be used for shaping analysis. 1688 * These bounds typically reflect changes in bidi level or font 1689 * metrics across which shaping does not occur. 1690 * 1691 * @param text the text to measure. Cannot be null. 1692 * @param start the index of the first character to measure 1693 * @param end the index past the last character to measure 1694 * @param contextStart the index of the first character to use for shaping context, 1695 * must be <= start 1696 * @param contextEnd the index past the last character to use for shaping context, 1697 * must be >= end 1698 * @param advances array to receive the advances, must have room for all advances, 1699 * can be null if only total advance is needed 1700 * @param advancesIndex the position in advances at which to put the 1701 * advance corresponding to the character at start 1702 * @return the total advance 1703 * 1704 * @hide 1705 */ 1706 public float getTextRunAdvances(String text, int start, int end, int contextStart, 1707 int contextEnd, float[] advances, int advancesIndex) { 1708 1709 if (text == null) { 1710 throw new IllegalArgumentException("text cannot be null"); 1711 } 1712 if ((start | end | contextStart | contextEnd | advancesIndex | (end - start) 1713 | (start - contextStart) | (contextEnd - end) 1714 | (text.length() - contextEnd) 1715 | (advances == null ? 0 : 1716 (advances.length - advancesIndex - (end - start)))) < 0) { 1717 throw new IndexOutOfBoundsException(); 1718 } 1719 1720 if (text.length() == 0 || start == end) { 1721 return 0f; 1722 } 1723 1724 if (!mHasCompatScaling) { 1725 return native_getTextRunAdvances(mNativePaint, text, start, end, 1726 contextStart, contextEnd, advances, advancesIndex); 1727 } 1728 1729 final float oldSize = getTextSize(); 1730 setTextSize(oldSize * mCompatScaling); 1731 float totalAdvance = native_getTextRunAdvances(mNativePaint, text, start, end, 1732 contextStart, contextEnd, advances, advancesIndex); 1733 setTextSize(oldSize); 1734 1735 if (advances != null) { 1736 for (int i = advancesIndex, e = i + (end - start); i < e; i++) { 1737 advances[i] *= mInvCompatScaling; 1738 } 1739 } 1740 return totalAdvance * mInvCompatScaling; // assume errors are insignificant 1741 } 1742 1743 /** 1744 * Returns the next cursor position in the run. This avoids placing the 1745 * cursor between surrogates, between characters that form conjuncts, 1746 * between base characters and combining marks, or within a reordering 1747 * cluster. 1748 * 1749 * <p>ContextStart and offset are relative to the start of text. 1750 * The context is the shaping context for cursor movement, generally 1751 * the bounds of the metric span enclosing the cursor in the direction of 1752 * movement. 1753 * 1754 * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid 1755 * cursor position, this returns -1. Otherwise this will never return a 1756 * value before contextStart or after contextStart + contextLength. 1757 * 1758 * @param text the text 1759 * @param contextStart the start of the context 1760 * @param contextLength the length of the context 1761 * @param offset the cursor position to move from 1762 * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER}, 1763 * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE}, 1764 * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT} 1765 * @return the offset of the next position, or -1 1766 * @hide 1767 */ 1768 public int getTextRunCursor(char[] text, int contextStart, int contextLength, 1769 int offset, int cursorOpt) { 1770 int contextEnd = contextStart + contextLength; 1771 if (((contextStart | contextEnd | offset | (contextEnd - contextStart) 1772 | (offset - contextStart) | (contextEnd - offset) 1773 | (text.length - contextEnd) | cursorOpt) < 0) 1774 || cursorOpt > CURSOR_OPT_MAX_VALUE) { 1775 throw new IndexOutOfBoundsException(); 1776 } 1777 1778 return native_getTextRunCursor(mNativePaint, text, 1779 contextStart, contextLength, offset, cursorOpt); 1780 } 1781 1782 /** 1783 * Returns the next cursor position in the run. This avoids placing the 1784 * cursor between surrogates, between characters that form conjuncts, 1785 * between base characters and combining marks, or within a reordering 1786 * cluster. 1787 * 1788 * <p>ContextStart, contextEnd, and offset are relative to the start of 1789 * text. The context is the shaping context for cursor movement, generally 1790 * the bounds of the metric span enclosing the cursor in the direction of 1791 * movement. 1792 * 1793 * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid 1794 * cursor position, this returns -1. Otherwise this will never return a 1795 * value before contextStart or after contextEnd. 1796 * 1797 * @param text the text 1798 * @param contextStart the start of the context 1799 * @param contextEnd the end of the context 1800 * @param offset the cursor position to move from 1801 * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER}, 1802 * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE}, 1803 * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT} 1804 * @return the offset of the next position, or -1 1805 * @hide 1806 */ 1807 public int getTextRunCursor(CharSequence text, int contextStart, 1808 int contextEnd, int offset, int cursorOpt) { 1809 1810 if (text instanceof String || text instanceof SpannedString || 1811 text instanceof SpannableString) { 1812 return getTextRunCursor(text.toString(), contextStart, contextEnd, 1813 offset, cursorOpt); 1814 } 1815 if (text instanceof GraphicsOperations) { 1816 return ((GraphicsOperations) text).getTextRunCursor( 1817 contextStart, contextEnd, offset, cursorOpt, this); 1818 } 1819 1820 int contextLen = contextEnd - contextStart; 1821 char[] buf = TemporaryBuffer.obtain(contextLen); 1822 TextUtils.getChars(text, contextStart, contextEnd, buf, 0); 1823 int result = getTextRunCursor(buf, 0, contextLen, offset - contextStart, cursorOpt); 1824 TemporaryBuffer.recycle(buf); 1825 return result; 1826 } 1827 1828 /** 1829 * Returns the next cursor position in the run. This avoids placing the 1830 * cursor between surrogates, between characters that form conjuncts, 1831 * between base characters and combining marks, or within a reordering 1832 * cluster. 1833 * 1834 * <p>ContextStart, contextEnd, and offset are relative to the start of 1835 * text. The context is the shaping context for cursor movement, generally 1836 * the bounds of the metric span enclosing the cursor in the direction of 1837 * movement. 1838 * 1839 * <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid 1840 * cursor position, this returns -1. Otherwise this will never return a 1841 * value before contextStart or after contextEnd. 1842 * 1843 * @param text the text 1844 * @param contextStart the start of the context 1845 * @param contextEnd the end of the context 1846 * @param offset the cursor position to move from 1847 * @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER}, 1848 * {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE}, 1849 * {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT} 1850 * @return the offset of the next position, or -1 1851 * @hide 1852 */ 1853 public int getTextRunCursor(String text, int contextStart, int contextEnd, 1854 int offset, int cursorOpt) { 1855 if (((contextStart | contextEnd | offset | (contextEnd - contextStart) 1856 | (offset - contextStart) | (contextEnd - offset) 1857 | (text.length() - contextEnd) | cursorOpt) < 0) 1858 || cursorOpt > CURSOR_OPT_MAX_VALUE) { 1859 throw new IndexOutOfBoundsException(); 1860 } 1861 1862 return native_getTextRunCursor(mNativePaint, text, 1863 contextStart, contextEnd, offset, cursorOpt); 1864 } 1865 1866 /** 1867 * Return the path (outline) for the specified text. 1868 * Note: just like Canvas.drawText, this will respect the Align setting in 1869 * the paint. 1870 * 1871 * @param text The text to retrieve the path from 1872 * @param index The index of the first character in text 1873 * @param count The number of characterss starting with index 1874 * @param x The x coordinate of the text's origin 1875 * @param y The y coordinate of the text's origin 1876 * @param path The path to receive the data describing the text. Must 1877 * be allocated by the caller. 1878 */ 1879 public void getTextPath(char[] text, int index, int count, 1880 float x, float y, Path path) { 1881 if ((index | count) < 0 || index + count > text.length) { 1882 throw new ArrayIndexOutOfBoundsException(); 1883 } 1884 native_getTextPath(mNativePaint, text, index, count, x, y, 1885 path.ni()); 1886 } 1887 1888 /** 1889 * Return the path (outline) for the specified text. 1890 * Note: just like Canvas.drawText, this will respect the Align setting 1891 * in the paint. 1892 * 1893 * @param text The text to retrieve the path from 1894 * @param start The first character in the text 1895 * @param end 1 past the last charcter in the text 1896 * @param x The x coordinate of the text's origin 1897 * @param y The y coordinate of the text's origin 1898 * @param path The path to receive the data describing the text. Must 1899 * be allocated by the caller. 1900 */ 1901 public void getTextPath(String text, int start, int end, 1902 float x, float y, Path path) { 1903 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1904 throw new IndexOutOfBoundsException(); 1905 } 1906 native_getTextPath(mNativePaint, text, start, end, x, y, 1907 path.ni()); 1908 } 1909 1910 /** 1911 * Return in bounds (allocated by the caller) the smallest rectangle that 1912 * encloses all of the characters, with an implied origin at (0,0). 1913 * 1914 * @param text String to measure and return its bounds 1915 * @param start Index of the first char in the string to measure 1916 * @param end 1 past the last char in the string measure 1917 * @param bounds Returns the unioned bounds of all the text. Must be 1918 * allocated by the caller. 1919 */ 1920 public void getTextBounds(String text, int start, int end, Rect bounds) { 1921 if ((start | end | (end - start) | (text.length() - end)) < 0) { 1922 throw new IndexOutOfBoundsException(); 1923 } 1924 if (bounds == null) { 1925 throw new NullPointerException("need bounds Rect"); 1926 } 1927 nativeGetStringBounds(mNativePaint, text, start, end, bounds); 1928 } 1929 1930 /** 1931 * Return in bounds (allocated by the caller) the smallest rectangle that 1932 * encloses all of the characters, with an implied origin at (0,0). 1933 * 1934 * @param text Array of chars to measure and return their unioned bounds 1935 * @param index Index of the first char in the array to measure 1936 * @param count The number of chars, beginning at index, to measure 1937 * @param bounds Returns the unioned bounds of all the text. Must be 1938 * allocated by the caller. 1939 */ 1940 public void getTextBounds(char[] text, int index, int count, Rect bounds) { 1941 if ((index | count) < 0 || index + count > text.length) { 1942 throw new ArrayIndexOutOfBoundsException(); 1943 } 1944 if (bounds == null) { 1945 throw new NullPointerException("need bounds Rect"); 1946 } 1947 nativeGetCharArrayBounds(mNativePaint, text, index, count, bounds); 1948 } 1949 1950 @Override 1951 protected void finalize() throws Throwable { 1952 try { 1953 finalizer(mNativePaint); 1954 } finally { 1955 super.finalize(); 1956 } 1957 } 1958 1959 private static native int native_init(); 1960 private static native int native_initWithPaint(int paint); 1961 private static native void native_reset(int native_object); 1962 private static native void native_set(int native_dst, int native_src); 1963 private static native int native_getStyle(int native_object); 1964 private static native void native_setStyle(int native_object, int style); 1965 private static native int native_getStrokeCap(int native_object); 1966 private static native void native_setStrokeCap(int native_object, int cap); 1967 private static native int native_getStrokeJoin(int native_object); 1968 private static native void native_setStrokeJoin(int native_object, 1969 int join); 1970 private static native boolean native_getFillPath(int native_object, 1971 int src, int dst); 1972 private static native int native_setShader(int native_object, int shader); 1973 private static native int native_setColorFilter(int native_object, 1974 int filter); 1975 private static native int native_setXfermode(int native_object, 1976 int xfermode); 1977 private static native int native_setPathEffect(int native_object, 1978 int effect); 1979 private static native int native_setMaskFilter(int native_object, 1980 int maskfilter); 1981 private static native int native_setTypeface(int native_object, 1982 int typeface); 1983 private static native int native_setRasterizer(int native_object, 1984 int rasterizer); 1985 1986 private static native int native_getTextAlign(int native_object); 1987 private static native void native_setTextAlign(int native_object, 1988 int align); 1989 1990 private static native void native_setTextLocale(int native_object, 1991 String locale); 1992 1993 private static native int native_getTextWidths(int native_object, 1994 char[] text, int index, int count, float[] widths); 1995 private static native int native_getTextWidths(int native_object, 1996 String text, int start, int end, float[] widths); 1997 1998 private static native float native_getTextRunAdvances(int native_object, 1999 char[] text, int index, int count, int contextIndex, int contextCount, 2000 float[] advances, int advancesIndex); 2001 private static native float native_getTextRunAdvances(int native_object, 2002 String text, int start, int end, int contextStart, int contextEnd, 2003 float[] advances, int advancesIndex); 2004 2005 private native int native_getTextRunCursor(int native_object, char[] text, 2006 int contextStart, int contextLength, int offset, int cursorOpt); 2007 private native int native_getTextRunCursor(int native_object, String text, 2008 int contextStart, int contextEnd, int offset, int cursorOpt); 2009 2010 private static native void native_getTextPath(int native_object, char[] text, 2011 int index, int count, float x, float y, int path); 2012 private static native void native_getTextPath(int native_object, String text, 2013 int start, int end, float x, float y, int path); 2014 private static native void nativeGetStringBounds(int nativePaint, 2015 String text, int start, int end, Rect bounds); 2016 private static native void nativeGetCharArrayBounds(int nativePaint, 2017 char[] text, int index, int count, Rect bounds); 2018 private static native void finalizer(int nativePaint); 2019} 2020