Added in API level 1

TextPaint


open class TextPaint : Paint

TextPaint is an extension of Paint that leaves room for some extra data used during text measuring and drawing.

Summary

Inherited constants
Int ANTI_ALIAS_FLAG

Paint flag that enables antialiasing when drawing.

Enabling this flag will cause all draw operations that support antialiasing to use it.

Notable draw operations that do not support antialiasing include:

Int CURSOR_AFTER

Option for getTextRunCursor. Compute the valid cursor after offset or the limit of the context, whichever is less.

Int CURSOR_AT

Option for getTextRunCursor. Return offset if the cursor at offset is valid, or -1 if it isn't.

Int CURSOR_AT_OR_AFTER

Option for getTextRunCursor. Compute the valid cursor at or after the offset or the limit of the context, whichever is less.

Int CURSOR_AT_OR_BEFORE

Option for getTextRunCursor. Compute the valid cursor at or before offset or the start of the context, whichever is greater.

Int CURSOR_BEFORE

Option for getTextRunCursor. Compute the valid cursor before offset or the start of the context, whichever is greater.

Int DEV_KERN_TEXT_FLAG

Legacy Paint flag, no longer used.

Int DITHER_FLAG

Paint flag that enables dithering when blitting.

Enabling this flag applies a dither to any blit operation where the target's colour space is more constrained than the source.

Int EMBEDDED_BITMAP_TEXT_FLAG

Paint flag that enables the use of bitmap fonts when drawing text.

Disabling this flag will prevent text draw operations from using embedded bitmap strikes in fonts, causing fonts with both scalable outlines and bitmap strikes to draw only the scalable outlines, and fonts with only bitmap strikes to not draw at all.

Int END_HYPHEN_EDIT_INSERT_ARMENIAN_HYPHEN

An integer representing the end of the line has Armentian hyphen (U+058A).

Int END_HYPHEN_EDIT_INSERT_HYPHEN

An integer representing the end of the line has normal hyphen character (U+002D).

Int END_HYPHEN_EDIT_INSERT_MAQAF

An integer representing the end of the line has maqaf (Hebrew hyphen, U+05BE).

Int END_HYPHEN_EDIT_INSERT_UCAS_HYPHEN

An integer representing the end of the line has Canadian Syllabics hyphen (U+1400).

Int END_HYPHEN_EDIT_INSERT_ZWJ_AND_HYPHEN

An integer representing the end of the line has Zero-Width-Joiner (U+200D) followed by normal hyphen character (U+002D).

Int END_HYPHEN_EDIT_NO_EDIT

An integer representing the end of the line has no modification for hyphenation.

Int END_HYPHEN_EDIT_REPLACE_WITH_HYPHEN

An integer representing the character at the end of the line is replaced with hyphen character (U+002D).

Int FAKE_BOLD_TEXT_FLAG

Paint flag that applies a synthetic bolding effect to drawn text.

Enabling this flag will cause text draw operations to apply a simulated bold effect when drawing a Typeface that is not already bold.

Int FILTER_BITMAP_FLAG

Paint flag that enables bilinear sampling on scaled bitmaps.

If cleared, scaled bitmaps will be drawn with nearest neighbor sampling, likely resulting in artifacts. This should generally be on when drawing bitmaps, unless performance-bound (rendering to software canvas) or preferring pixelation artifacts to blurriness when scaling significantly.

If bitmaps are scaled for device density at creation time (as resource bitmaps often are) the filtering will already have been done.

On devices running Build.VERSION_CODES.O and below, hardware accelerated drawing always uses bilinear sampling on scaled bitmaps, regardless of this flag. On devices running Build.VERSION_CODES.Q and above, this flag defaults to being set on a new Paint. It can be cleared with setFlags or setFilterBitmap.

Int HINTING_OFF

Font hinter option that disables font hinting.

Int HINTING_ON

Font hinter option that enables font hinting.

Int LINEAR_TEXT_FLAG

Paint flag that enables smooth linear scaling of text.

Enabling this flag does not actually scale text, but rather adjusts text draw operations to deal gracefully with smooth adjustment of scale. When this flag is enabled, font hinting is disabled to prevent shape deformation between scale factors, and glyph caching is disabled due to the large number of glyph images that will be generated.

SUBPIXEL_TEXT_FLAG should be used in conjunction with this flag to prevent glyph positions from snapping to whole pixel values as scale factor is adjusted.

Int START_HYPHEN_EDIT_INSERT_HYPHEN

An integer representing the starting of the line has normal hyphen character (U+002D).

Int START_HYPHEN_EDIT_INSERT_ZWJ

An integer representing the starting of the line has Zero-Width-Joiner (U+200D).

Int START_HYPHEN_EDIT_NO_EDIT

An integer representing the starting of the line has no modification for hyphenation.

Int STRIKE_THRU_TEXT_FLAG

Paint flag that applies a strike-through decoration to drawn text.

Int SUBPIXEL_TEXT_FLAG

Paint flag that enables subpixel positioning of text.

Enabling this flag causes glyph advances to be computed with subpixel accuracy.

This can be used with LINEAR_TEXT_FLAG to prevent text from jittering during smooth scale transitions.

Int TEXT_RUN_FLAG_LEFT_EDGE

A text run flag that indicates the run is located the visually most left segment of the line.

This flag is used for telling the underlying text layout engine that the text is located at the most left of the line. This flag is used for controlling the amount letter spacing added. If the text is in the middle of the line, the text layout engine assigns additional letter spacing to the both side of each letter. On the other hand, the letter spacing should not be added to the visually most left and right of the line. By setting this flag, text layout engine calculates the layout as it is located at the most visually left of the line and doesn't add letter spacing to the left of this run.

Note that the caller must resolve BiDi runs and reorder them visually and set this flag only if the target run is located visually most left position. This left does not always mean the beginning of the text.

If the run covers entire line, caller should set TEXT_RUN_FLAG_RIGHT_EDGE as well.

Note that this flag is only effective for run based APIs. For example, this flag works for Canvas.drawTextRun(CharSequence, int, int, int, int, float, float, boolean, Paint) and Paint.getRunCharacterAdvance(char[], int, int, int, int, boolean, int, float[], int). However, this doesn't work for Canvas.drawText(CharSequence, int, int, float, float, Paint) or Paint.measureText(CharSequence, int, int). The non-run based APIs works as both TEXT_RUN_FLAG_LEFT_EDGE and TEXT_RUN_FLAG_RIGHT_EDGE are specified.

Int TEXT_RUN_FLAG_RIGHT_EDGE

A text run flag that indicates the run is located the visually most right segment of the line.

This flag is used for telling the underlying text layout engine that the text is located at the most right of the line. This flag is used for controlling the amount letter spacing added. If the text is in the middle of the line, the text layout engine assigns additional letter spacing to the both side of each letter. On the other hand, the letter spacing should not be added to the visually most left and right of the line. By setting this flag, text layout engine calculates the layout as it is located at the most visually left of the line and doesn't add letter spacing to the left of this run.

Note that the caller must resolve BiDi runs and reorder them visually and set this flag only if the target run is located visually most right position. This right does not always mean the end of the text.

If the run covers entire line, caller should set TEXT_RUN_FLAG_LEFT_EDGE as well.

Note that this flag is only effective for run based APIs. For example, this flag works for Canvas.drawTextRun(CharSequence, int, int, int, int, float, float, boolean, Paint) and Paint.getRunCharacterAdvance(char[], int, int, int, int, boolean, int, float[], int). However, this doesn't work for Canvas.drawText(CharSequence, int, int, float, float, Paint) or Paint.measureText(CharSequence, int, int). The non-run based APIs works as both TEXT_RUN_FLAG_LEFT_EDGE and TEXT_RUN_FLAG_RIGHT_EDGE are specified.

Int UNDERLINE_TEXT_FLAG

Paint flag that applies an underline decoration to drawn text.

Int VERTICAL_TEXT_FLAG

A flat that controls text to be written in vertical orientation

This flag is used for telling the underlying text layout engine that the text is for vertical direction. By enabling this flag, text measurement, drawing and shaping APIs works for vertical text layout. For example, Canvas.drawText(String, float, float, Paint) draws text from top to bottom. Paint.measureText(String) returns vertical advances instead of horizontal advances. TextRunShaper shapes text vertically and report glyph IDs for vertical layout.

Do not set this flag for making android.text.Layout. The android.text.Layout class and its subclasses are designed for horizontal text only and does not work for vertical text.

Public constructors

TextPaint(flags: Int)

Public methods
open Unit
set(tp: TextPaint!)

Copy the fields from tp into this TextPaint, including the fields inherited from Paint.

Inherited functions
Float ascent()

Return the distance above (negative) the baseline (ascent) based on the current typeface and text size.

Note that this is the ascent of the main typeface, and actual text rendered may need a larger ascent because fallback fonts may get used in rendering the text.

Int breakText(text: CharArray!, index: Int, count: Int, maxWidth: Float, measuredWidth: FloatArray!)

Measure the text, stopping early if the measured width exceeds maxWidth. Return the number of chars that were measured, and if measuredWidth is not null, return in it the actual width measured.

Int breakText(text: CharSequence!, start: Int, end: Int, measureForwards: Boolean, maxWidth: Float, measuredWidth: FloatArray!)

Measure the text, stopping early if the measured width exceeds maxWidth. Return the number of chars that were measured, and if measuredWidth is not null, return in it the actual width measured.

Int breakText(text: String!, measureForwards: Boolean, maxWidth: Float, measuredWidth: FloatArray!)

Measure the text, stopping early if the measured width exceeds maxWidth. Return the number of chars that were measured, and if measuredWidth is not null, return in it the actual width measured.

Unit clearShadowLayer()

Clear the shadow layer.

Float descent()

Return the distance below (positive) the baseline (descent) based on the current typeface and text size.

Note that this is the descent of the main typeface, and actual text rendered may need a larger descent because fallback fonts may get used in rendering the text.

Boolean equalsForTextMeasurement(other: Paint)

Returns true of the passed Paint will have the same effect on text measurement

Int getAlpha()

Helper to getColor() that just returns the color's alpha value. This is the same as calling getColor() >>> 24. It always returns a value between 0 (completely transparent) and 255 (completely opaque).

BlendMode? getBlendMode()

Get the paint's blend mode object. Will return null if there is a Xfermode applied that cannot be represented by a blend mode (i.e. a custom RuntimeXfermode

Int getColor()

Return the paint's color in sRGB. Note that the color is a 32bit value containing alpha as well as r,g,b. This 32bit value is not premultiplied, meaning that its alpha can be any value, regardless of the values of r,g,b. See the Color class for more details.

ColorFilter! getColorFilter()

Get the paint's colorfilter (maybe be null).

Long getColorLong()

Return the paint's color. Note that the color is a long with an encoded ColorSpace as well as alpha and r,g,b. These values are not premultiplied, meaning that alpha can be any value, regardless of the values of r,g,b. See the Color class for more details.

Int getEndHyphenEdit()

Get the current value of end hyphen edit. The default value is 0 which is equivalent to END_HYPHEN_EDIT_NO_EDIT.

Boolean getFillPath(src: Path!, dst: Path!)

Applies any/all effects (patheffect, stroking) to src, returning the result in dst. The result is that drawing src with this paint will be the same as drawing dst with a default paint (at least from the geometric perspective).

Int getFlags()

Return the paint's flags. Use the Flag enum to test flag values.

String! getFontFeatureSettings()

Returns the font feature settings. The format is the same as the CSS font-feature-settings attribute: https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop

Paint.FontMetrics! getFontMetrics()

Allocates a new FontMetrics object, and then calls getFontMetrics(fm) with it, returning the object.

Float getFontMetrics(metrics: Paint.FontMetrics!)

Return the font's recommended interline spacing, given the Paint's settings for typeface, textSize, etc. If metrics is not null, return the fontmetric values in it.

Note that these are the values for the main typeface, and actual text rendered may need a larger set of values because fallback fonts may get used in rendering the text.

Unit getFontMetricsForLocale(metrics: Paint.FontMetrics)

Get the font metrics used for the locale Obtain the metrics of the font that is used for the specified locale by setTextLocales(android.os.LocaleList). If multiple locales are specified, the minimum ascent and maximum descent will be set. This API is useful for determining the default line height of the empty text field, e.g. android.widget.EditText. Note, if the android.graphics.Typeface is created from the custom font files, its metrics are reserved, i.e. the ascent will be the custom font's ascent or smaller, the descent will be the custom font's descent or larger. Note, if the android.graphics.Typeface is a system fallback, e.g. android.graphics.Typeface#SERIF, the default font's metrics are reserved, i.e. the ascent will be the serif font's ascent or smaller, the descent will be the serif font's descent or larger.

Paint.FontMetricsInt! getFontMetricsInt()

Int getFontMetricsInt(fmi: Paint.FontMetricsInt!)

Return the font's interline spacing, given the Paint's settings for typeface, textSize, etc. If metrics is not null, return the fontmetric values in it. Note: all values have been converted to integers from floats, in such a way has to make the answers useful for both spacing and clipping. If you want more control over the rounding, call getFontMetrics().

Note that these are the values for the main typeface, and actual text rendered may need a larger set of values because fallback fonts may get used in rendering the text.

Unit getFontMetricsInt(text: CharArray, start: Int, count: Int, contextStart: Int, contextCount: Int, isRtl: Boolean, outMetrics: Paint.FontMetricsInt)

Returns the font metrics value for the given text. If the text is rendered with multiple font files, this function returns the large ascent and descent that are enough for drawing all font files. The context range is used for shaping context. Some script, e.g. Arabic or Devanagari, changes letter shape based on its location or surrounding characters.

Unit getFontMetricsInt(text: CharSequence, start: Int, count: Int, contextStart: Int, contextCount: Int, isRtl: Boolean, outMetrics: Paint.FontMetricsInt)

Returns the font metrics value for the given text. If the text is rendered with multiple font files, this function returns the large ascent and descent that are enough for drawing all font files. The context range is used for shaping context. Some script, e.g. Arabic or Devanagari, changes letter shape based on its location or surrounding characters.

Unit getFontMetricsIntForLocale(metrics: Paint.FontMetricsInt)

Get the font metrics used for the locale Obtain the metrics of the font that is used for the specified locale by setTextLocales(android.os.LocaleList). If multiple locales are specified, the minimum ascent and maximum descent will be set. This API is useful for determining the default line height of the empty text field, e.g. android.widget.EditText. Note, if the android.graphics.Typeface is created from the custom font files, its metrics are reserved, i.e. the ascent will be the custom font's ascent or smaller, the descent will be the custom font's descent or larger. Note, if the android.graphics.Typeface is a system fallback, e.g. android.graphics.Typeface#SERIF, the default font's metrics are reserved, i.e. the ascent will be the serif font's ascent or smaller, the descent will be the serif font's descent or larger.

Float getFontSpacing()

Return the recommend line spacing based on the current typeface and text size.

Note that this is the value for the main typeface, and actual text rendered may need a larger value because fallback fonts may get used in rendering the text.

String! getFontVariationSettings()

Returns the font variation settings.

Int getHinting()

Return the paint's hinting mode. Returns either HINTING_OFF or HINTING_ON.

Float getLetterSpacing()

Return the paint's letter-spacing for text. The default value is 0.

MaskFilter! getMaskFilter()

Get the paint's maskfilter object.

Int getOffsetForAdvance(text: CharArray!, start: Int, end: Int, contextStart: Int, contextEnd: Int, isRtl: Boolean, advance: Float)

Get the character offset within the string whose position is closest to the specified horizontal position.

The returned value is generally the value of offset for which #getRunAdvance yields a result most closely approximating advance, and which is also on a grapheme cluster boundary. As such, it is the preferred method for positioning a cursor in response to a touch or pointer event. The grapheme cluster boundaries are based on Unicode Standard Annex #29 but with some tailoring for better user experience.

Note that advance is a (generally positive) width measurement relative to the start of the run. Thus, for RTL runs it the distance from the point to the right edge.

All indices are relative to the start of text. Further, 0 <= contextStart <= start <= end <= contextEnd <= text.length must hold on entry, and start <= result <= end will hold on return.

Int getOffsetForAdvance(text: CharSequence!, start: Int, end: Int, contextStart: Int, contextEnd: Int, isRtl: Boolean, advance: Float)

PathEffect! getPathEffect()

Get the paint's patheffect object.

Float getRunAdvance(text: CharArray!, start: Int, end: Int, contextStart: Int, contextEnd: Int, isRtl: Boolean, offset: Int)

Measure cursor position within a run of text.

The run of text includes the characters from start to end in the text. In addition, the range contextStart to contextEnd is used as context for the purpose of complex text shaping, such as Arabic text potentially shaped differently based on the text next to it.

All text outside the range contextStart..contextEnd is ignored. The text between start and end will be laid out to be measured.

The returned width measurement is the advance from start to offset. It is generally a positive value, no matter the direction of the run. If offset == end, the return value is simply the width of the whole run from start to end.

Ligatures are formed for characters in the range start..end (but not for start..contextStart or end..contextEnd). If offset points to a character in the middle of such a formed ligature, but at a grapheme cluster boundary, the return value will also reflect an advance in the middle of the ligature. See #getOffsetForAdvance for more discussion of grapheme cluster boundaries.

The direction of the run is explicitly specified by isRtl. Thus, this method is suitable only for runs of a single direction.

All indices are relative to the start of text. Further, 0 <= contextStart <= start <= offset <= end <= contextEnd <= text.length must hold on entry.

Float getRunAdvance(text: CharSequence!, start: Int, end: Int, contextStart: Int, contextEnd: Int, isRtl: Boolean, offset: Int)

Float getRunCharacterAdvance(text: CharArray, start: Int, end: Int, contextStart: Int, contextEnd: Int, isRtl: Boolean, offset: Int, advances: FloatArray?, advancesIndex: Int)

Measure the advance of each character within a run of text and also return the cursor position within the run.

Float getRunCharacterAdvance(text: CharSequence, start: Int, end: Int, contextStart: Int, contextEnd: Int, isRtl: Boolean, offset: Int, advances: FloatArray?, advancesIndex: Int)

Shader! getShader()

Get the paint's shader object.

Int getShadowLayerColor()

Returns the color of the shadow layer.

Long getShadowLayerColorLong()

Returns the color of the shadow layer.

Float getShadowLayerDx()

Returns the x offset of the shadow layer.

Float getShadowLayerDy()

Returns the y offset of the shadow layer.

Float getShadowLayerRadius()

Returns the blur radius of the shadow layer.

Int getStartHyphenEdit()

Get the current value of start hyphen edit. The default value is 0 which is equivalent to START_HYPHEN_EDIT_NO_EDIT.

Float getStrikeThruPosition()

Distance from top of the strike-through line to the baseline in pixels. The result is negative for positions that are above the baseline. This method returns where the strike-through line should be drawn independent of if the STRIKE_THRU_TEXT_FLAG bit is set.
The units of this value are pixels.

Float getStrikeThruThickness()

Returns the thickness of the strike-through line in pixels.
The units of this value are pixels.

Paint.Cap! getStrokeCap()

Return the paint's Cap, controlling how the start and end of stroked lines and paths are treated.

Paint.Join! getStrokeJoin()

Return the paint's stroke join type.

Float getStrokeMiter()

Return the paint's stroke miter value. Used to control the behavior of miter joins when the joins angle is sharp.

Float getStrokeWidth()

Return the width for stroking.

A value of 0 strokes in hairline mode. Hairlines always draws a single pixel independent of the canvas's matrix.

Paint.Style! getStyle()

Return the paint's style, used for controlling how primitives' geometries are interpreted (except for drawBitmap, which always assumes FILL_STYLE).

Paint.Align! getTextAlign()

Return the paint's Align value for drawing text. This controls how the text is positioned relative to its origin. LEFT align means that all of the text will be drawn to the right of its origin (i.e. the origin specifies the LEFT edge of the text) and so on.

Unit getTextBounds(text: CharArray!, index: Int, count: Int, bounds: Rect!)

Return in bounds (allocated by the caller) the smallest rectangle that encloses all of the characters, with an implied origin at (0,0).

Unit getTextBounds(text: CharSequence, start: Int, end: Int, bounds: Rect)

Retrieve the text boundary box and store to bounds. Return in bounds (allocated by the caller) the smallest rectangle that encloses all of the characters, with an implied origin at (0,0). Note that styles are ignored even if you pass android.text.Spanned instance. Use android.text.StaticLayout for measuring bounds of android.text.Spanned.

Unit getTextBounds(text: String!, start: Int, end: Int, bounds: Rect!)

Retrieve the text boundary box and store to bounds. Return in bounds (allocated by the caller) the smallest rectangle that encloses all of the characters, with an implied origin at (0,0).

Locale getTextLocale()

Get the text's primary Locale. Note that this is not all of the locale-related information Paint has. Use getTextLocales() to get the complete list.

LocaleList getTextLocales()

Get the text locale list.

Unit getTextPath(text: CharArray!, index: Int, count: Int, x: Float, y: Float, path: Path!)

Return the path (outline) for the specified text. Note: just like Canvas.drawText, this will respect the Align setting in the paint.

Unit getTextPath(text: String!, start: Int, end: Int, x: Float, y: Float, path: Path!)

Return the path (outline) for the specified text. Note: just like Canvas.drawText, this will respect the Align setting in the paint.

Float getTextRunAdvances(chars: CharArray, index: Int, count: Int, contextIndex: Int, contextCount: Int, isRtl: Boolean, advances: FloatArray?, advancesIndex: Int)

Retrieve the character advances of the text. Returns the total advance width for the characters in the run from index for count of chars, and if advances is not null, the advance assigned to each of these characters (java chars).

The trailing surrogate in a valid surrogate pair is assigned an advance of 0. Thus the number of returned advances is always equal to count, not to the number of unicode codepoints represented by the run.

In the case of conjuncts or combining marks, the total advance is assigned to the first logical character, and the following characters are assigned an advance of 0.

This generates the sum of the advances of glyphs for characters in a reordered cluster as the width of the first logical character in the cluster, and 0 for the widths of all other characters in the cluster. In effect, such clusters are treated like conjuncts.

The shaping bounds limit the amount of context available outside start and end that can be used for shaping analysis. These bounds typically reflect changes in bidi level or font metrics across which shaping does not occur.

Int getTextRunCursor(text: CharArray, contextStart: Int, contextLength: Int, isRtl: Boolean, offset: Int, cursorOpt: Int)

Returns the next cursor position in the run. This avoids placing the cursor between surrogates, between characters that form conjuncts, between base characters and combining marks, or within a reordering cluster.

ContextStart and offset are relative to the start of text. The context is the shaping context for cursor movement, generally the bounds of the metric span enclosing the cursor in the direction of movement.

If cursorOpt is CURSOR_AT and the offset is not a valid cursor position, this returns -1. Otherwise this will never return a value before contextStart or after contextStart + contextLength.

Int getTextRunCursor(text: CharSequence, contextStart: Int, contextEnd: Int, isRtl: Boolean, offset: Int, cursorOpt: Int)

Returns the next cursor position in the run. This avoids placing the cursor between surrogates, between characters that form conjuncts, between base characters and combining marks, or within a reordering cluster.

ContextStart, contextEnd, and offset are relative to the start of text. The context is the shaping context for cursor movement, generally the bounds of the metric span enclosing the cursor in the direction of movement.

If cursorOpt is CURSOR_AT and the offset is not a valid cursor position, this returns -1. Otherwise this will never return a value before contextStart or after contextEnd.

Float getTextScaleX()

Return the paint's horizontal scale factor for text. The default value is 1.0.

Float getTextSize()

Return the paint's text size.

Float getTextSkewX()

Return the paint's horizontal skew factor for text. The default value is 0.

Int getTextWidths(text: CharArray!, index: Int, count: Int, widths: FloatArray!)

Return the advance widths for the characters in the string.

Int getTextWidths(text: CharSequence!, start: Int, end: Int, widths: FloatArray!)

Return the advance widths for the characters in the string.

Int getTextWidths(text: String!, widths: FloatArray!)

Return the advance widths for the characters in the string.

Int getTextWidths(text: String!, start: Int, end: Int, widths: FloatArray!)

Return the advance widths for the characters in the string.

Typeface! getTypeface()

Get the paint's typeface object.

The typeface object identifies which font to use when drawing or measuring text.

Float getUnderlinePosition()

Returns the distance from top of the underline to the baseline in pixels. The result is positive for positions that are below the baseline. This method returns where the underline should be drawn independent of if the UNDERLINE_TEXT_FLAG bit is set.
The units of this value are pixels.

Float getWordSpacing()

Return the paint's extra word-spacing for text. The default value is 0.
The units of this value are pixels.

Xfermode! getXfermode()

Get the paint's transfer mode object.

Boolean hasGlyph(string: String!)

Determine whether the typeface set on the paint has a glyph supporting the string. The simplest case is when the string contains a single character, in which this method determines whether the font has the character. In the case of multiple characters, the method returns true if there is a single glyph representing the ligature. For example, if the input is a pair of regional indicator symbols, determine whether there is an emoji flag for the pair.

Finally, if the string contains a variation selector, the method only returns true if the fonts contains a glyph specific to that variation.

Checking is done on the entire fallback chain, not just the immediate font referenced.

Boolean isAntiAlias()

Helper for getFlags(), returning true if ANTI_ALIAS_FLAG bit is set AntiAliasing smooths out the edges of what is being drawn, but is has no impact on the interior of the shape. See setDither() and setFilterBitmap() to affect how colors are treated.

Boolean isDither()

Helper for getFlags(), returning true if DITHER_FLAG bit is set Dithering affects how colors that are higher precision than the device are down-sampled. No dithering is generally faster, but higher precision colors are just truncated down (e.g. 8888 -> 565). Dithering tries to distribute the error inherent in this process, to reduce the visual artifacts.

Boolean isElegantTextHeight()

Get the elegant metrics flag. Note: For applications target API 35 or later, this function returns true by default. For applications target API 36 or later, the function call will be ignored and the elegant text height is always enabled.

Boolean isFakeBoldText()

Helper for getFlags(), returning true if FAKE_BOLD_TEXT_FLAG bit is set

Boolean isFilterBitmap()

Whether or not the bitmap filter is activated. Filtering affects the sampling of bitmaps when they are transformed. Filtering does not affect how the colors in the bitmap are converted into device pixels. That is dependent on dithering and xfermodes.

Boolean isLinearText()

Helper for getFlags(), returning true if LINEAR_TEXT_FLAG bit is set

Boolean isStrikeThruText()

Helper for getFlags(), returning true if STRIKE_THRU_TEXT_FLAG bit is set

Boolean isSubpixelText()

Helper for getFlags(), returning true if SUBPIXEL_TEXT_FLAG bit is set

Boolean isUnderlineText()

Helper for getFlags(), returning true if UNDERLINE_TEXT_FLAG bit is set

Float measureText(text: CharArray!, index: Int, count: Int)

Return the width of the text.

Float measureText(text: CharSequence!, start: Int, end: Int)

Return the width of the text.

Float measureText(text: String!)

Return the width of the text.

Float measureText(text: String!, start: Int, end: Int)

Return the width of the text.

Unit reset()

Restores the paint to its default settings.

Unit set(src: Paint!)

Copy the fields from src into this paint. This is equivalent to calling get() on all of the src fields, and calling the corresponding set() methods on this.

Unit setARGB(a: Int, r: Int, g: Int, b: Int)

Helper to setColor(), that takes a,r,g,b and constructs the color int

Unit setAlpha(a: Int)

Helper to setColor(), that only assigns the color's alpha value, leaving its r,g,b values unchanged. Results are undefined if the alpha value is outside of the range [0..255]

Unit setAntiAlias(aa: Boolean)

Helper for setFlags(), setting or clearing the ANTI_ALIAS_FLAG bit AntiAliasing smooths out the edges of what is being drawn, but is has no impact on the interior of the shape. See setDither() and setFilterBitmap() to affect how colors are treated.

Unit setBlendMode(blendmode: BlendMode?)

Set or clear the blend mode. A blend mode defines how source pixels (generated by a drawing command) are composited with the destination pixels (content of the render target).

Pass null to clear any previous blend mode.

Unit setColor(color: Int)

Set the paint's color. Note that the color is an int containing alpha as well as r,g,b. This 32bit value is not premultiplied, meaning that its alpha can be any value, regardless of the values of r,g,b. See the Color class for more details.

Unit setColor(color: Long)

Set the paint's color with a ColorLong. Note that the color is a long with an encoded ColorSpace as well as alpha and r,g,b. These values are not premultiplied, meaning that alpha can be any value, regardless of the values of r,g,b. See the Color class for more details.

ColorFilter! setColorFilter(filter: ColorFilter!)

Set or clear the paint's colorfilter, returning the parameter.

Unit setDither(dither: Boolean)

Helper for setFlags(), setting or clearing the DITHER_FLAG bit Dithering affects how colors that are higher precision than the device are down-sampled. No dithering is generally faster, but higher precision colors are just truncated down (e.g. 8888 -> 565). Dithering tries to distribute the error inherent in this process, to reduce the visual artifacts.

Unit setElegantTextHeight(elegant: Boolean)

Set the paint's elegant height metrics flag. This setting selects font variants that have not been compacted to fit Latin-based vertical metrics, and also increases top and bottom bounds to provide more space.

Note: For applications target API 35 or later, the default value will be true by default. For applications target API 36 or later, the function call will be ignored and the elegant text height is always enabled.

Unit setEndHyphenEdit(endHyphen: Int)

Set a end hyphen edit on the paint. By setting end hyphen edit, the measurement and drawing is performed with modifying hyphenation at the end of line. For example, by passing END_HYPHEN_EDIT_INSERT_HYPHEN like as follows, HYPHEN(U+2010) character is appended at the end of line.

<code>
    Paint paint = new Paint();
    paint.setEndHyphenEdit(Paint.END_HYPHEN_EDIT_INSERT_HYPHEN);
    paint.measureText("abc", 0, 3);  // Returns the width of "abc-"
    Canvas.drawText("abc", 0, 3, 0f, 0f, paint);  // Draws "abc-"
  </code>
The default value is 0 which is equivalent to END_HYPHEN_EDIT_NO_EDIT.

Unit setFakeBoldText(fakeBoldText: Boolean)

Helper for setFlags(), setting or clearing the FAKE_BOLD_TEXT_FLAG bit

Unit setFilterBitmap(filter: Boolean)

Helper for setFlags(), setting or clearing the FILTER_BITMAP_FLAG bit. Filtering affects the sampling of bitmaps when they are transformed. Filtering does not affect how the colors in the bitmap are converted into device pixels. That is dependent on dithering and xfermodes.

Unit setFlags(flags: Int)

Set the paint's flags. Use the Flag enum to specific flag values.

Unit setFontFeatureSettings(settings: String!)

Set font feature settings. The format is the same as the CSS font-feature-settings attribute: https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop

Boolean setFontVariationSettings(fontVariationSettings: String!)

Sets TrueType or OpenType font variation settings. The settings string is constructed from multiple pairs of axis tag and style values. The axis tag must contain four ASCII characters and must be wrapped with single quotes (U+0027) or double quotes (U+0022). Axis strings that are longer or shorter than four characters, or contain characters outside of U+0020..U+007E are invalid. If a specified axis name is not defined in the font, the settings will be ignored. Examples,

  • Set font width to 150.
    <code>
        Paint paint = new Paint();
        paint.setFontVariationSettings("'wdth' 150");
      </code>
  • Set the font slant to 20 degrees and ask for italic style.
    <code>
        Paint paint = new Paint();
        paint.setFontVariationSettings("'slnt' 20, 'ital' 1");
      </code>

Unit setHinting(mode: Int)

Set the paint's hinting mode. May be either HINTING_OFF or HINTING_ON.

Unit setLetterSpacing(letterSpacing: Float)

Set the paint's letter-spacing for text. The default value is 0. The value is in 'EM' units. Typical values for slight expansion will be around 0.05. Negative values tighten text.

Unit setLinearText(linearText: Boolean)

Helper for setFlags(), setting or clearing the LINEAR_TEXT_FLAG bit

MaskFilter! setMaskFilter(maskfilter: MaskFilter!)

Set or clear the maskfilter object.

Pass null to clear any previous maskfilter. As a convenience, the parameter passed is also returned.

PathEffect! setPathEffect(effect: PathEffect!)

Set or clear the patheffect object.

Pass null to clear any previous patheffect. As a convenience, the parameter passed is also returned.

Shader! setShader(shader: Shader!)

Set or clear the shader object.

Pass null to clear any previous shader. As a convenience, the parameter passed is also returned.

Unit setShadowLayer(radius: Float, dx: Float, dy: Float, shadowColor: Int)

This draws a shadow layer below the main layer, with the specified offset and color, and blur radius. If radius is 0, then the shadow layer is removed.

Can be used to create a blurred shadow underneath text. Support for use with other drawing operations is constrained to the software rendering pipeline.

The alpha of the shadow will be the paint's alpha if the shadow color is opaque, or the alpha from the shadow color if not.

Unit setShadowLayer(radius: Float, dx: Float, dy: Float, shadowColor: Long)

This draws a shadow layer below the main layer, with the specified offset and color, and blur radius. If radius is 0, then the shadow layer is removed.

Can be used to create a blurred shadow underneath text. Support for use with other drawing operations is constrained to the software rendering pipeline.

The alpha of the shadow will be the paint's alpha if the shadow color is opaque, or the alpha from the shadow color if not.

Unit setStartHyphenEdit(startHyphen: Int)

Set a start hyphen edit on the paint. By setting start hyphen edit, the measurement and drawing is performed with modifying hyphenation at the start of line. For example, by passing START_HYPHEN_EDIT_INSERT_HYPHEN like as follows, HYPHEN(U+2010) character is appended at the start of line.

<code>
    Paint paint = new Paint();
    paint.setStartHyphenEdit(Paint.START_HYPHEN_EDIT_INSERT_HYPHEN);
    paint.measureText("abc", 0, 3);  // Returns the width of "-abc"
    Canvas.drawText("abc", 0, 3, 0f, 0f, paint);  // Draws "-abc"
  </code>
The default value is 0 which is equivalent to START_HYPHEN_EDIT_NO_EDIT.

Unit setStrikeThruText(strikeThruText: Boolean)

Helper for setFlags(), setting or clearing the STRIKE_THRU_TEXT_FLAG bit

Unit setStrokeCap(cap: Paint.Cap!)

Set the paint's Cap.

Unit setStrokeJoin(join: Paint.Join!)

Set the paint's Join.

Unit setStrokeMiter(miter: Float)

Set the paint's stroke miter value. This is used to control the behavior of miter joins when the joins angle is sharp. This value must be >= 0.

Unit setStrokeWidth(width: Float)

Set the width for stroking. Pass 0 to stroke in hairline mode. Hairlines always draws a single pixel independent of the canvas's matrix.

Unit setStyle(style: Paint.Style!)

Set the paint's style, used for controlling how primitives' geometries are interpreted (except for drawBitmap, which always assumes Fill).

Unit setSubpixelText(subpixelText: Boolean)

Helper for setFlags(), setting or clearing the SUBPIXEL_TEXT_FLAG bit

Unit setTextAlign(align: Paint.Align!)

Set the paint's text alignment. This controls how the text is positioned relative to its origin. LEFT align means that all of the text will be drawn to the right of its origin (i.e. the origin specifies the LEFT edge of the text) and so on.

Unit setTextLocale(locale: Locale)

Set the text locale list to a one-member list consisting of just the locale. See setTextLocales(android.os.LocaleList) for how the locale list affects the way the text is drawn for some languages.

Unit setTextLocales(locales: LocaleList)

Set the text locale list. The text locale list affects how the text is drawn for some languages. For example, if the locale list contains Locale.CHINESE or Locale.CHINA, then the text renderer will prefer to draw text using a Chinese font. Likewise, if the locale list contains Locale.JAPANESE or Locale.JAPAN, then the text renderer will prefer to draw text using a Japanese font. If the locale list contains both, the order those locales appear in the list is considered for deciding the font. This distinction is important because Chinese and Japanese text both use many of the same Unicode code points but their appearance is subtly different for each language. By default, the text locale list is initialized to a one-member list just containing the system locales. This assumes that the text to be rendered will most likely be in the user's preferred language. If the actual language or languages of the text is/are known, then they can be provided to the text renderer using this method. The text renderer may attempt to guess the language script based on the contents of the text to be drawn independent of the text locale here. Specifying the text locales just helps it do a better job in certain ambiguous cases.

Unit setTextScaleX(scaleX: Float)

Set the paint's horizontal scale factor for text. The default value is 1.0. Values > 1.0 will stretch the text wider. Values < 1.0 will stretch the text narrower.

Unit setTextSize(textSize: Float)

Set the paint's text size. This value must be > 0

Unit setTextSkewX(skewX: Float)

Set the paint's horizontal skew factor for text. The default value is 0. For approximating oblique text, use values around -0.25.

Typeface! setTypeface(typeface: Typeface!)

Set or clear the typeface object.

Pass null to clear any previous typeface. As a convenience, the parameter passed is also returned.

Unit setUnderlineText(underlineText: Boolean)

Helper for setFlags(), setting or clearing the UNDERLINE_TEXT_FLAG bit

Unit setWordSpacing(wordSpacing: Float)

Set the paint's extra word-spacing for text. Increases the white space width between words with the given amount of pixels. The default value is 0.

Xfermode! setXfermode(xfermode: Xfermode!)

Set or clear the transfer mode object. A transfer mode defines how source pixels (generate by a drawing command) are composited with the destination pixels (content of the render target).

Pass null to clear any previous transfer mode. As a convenience, the parameter passed is also returned.

PorterDuffXfermode is the most common transfer mode.

Properties
Int

Int

Float

IntArray!

Int

Int

Special value 0 means no custom underline

Float

Thickness of the underline, in pixels.

Public constructors

TextPaint

Added in API level 1
TextPaint()

TextPaint

Added in API level 1
TextPaint(p: Paint!)

TextPaint

Added in API level 1
TextPaint(flags: Int)

Public methods

set

Added in API level 1
open fun set(tp: TextPaint!): Unit

Copy the fields from tp into this TextPaint, including the fields inherited from Paint.

Properties

baselineShift

Added in API level 1
var baselineShift: Int

bgColor

Added in API level 1
var bgColor: Int

density

Added in API level 5
var density: Float

drawableState

Added in API level 1
var drawableState: IntArray!

linkColor

Added in API level 1
var linkColor: Int

underlineColor

Added in API level 29
var underlineColor: Int

Special value 0 means no custom underline

underlineThickness

Added in API level 29
var underlineThickness: Float

Thickness of the underline, in pixels.
The units of this value are pixels.