HenCoder Android 開發進階:自定義 View 1-3 文字的繪制
Canvas 繪制文字的方式
drawText()
最基本的繪制文字的方法
drawTextRun()
drawTextOnPath()
沿著一條 Path 來繪制文字。這是一個耍雜技的方法。
StaticLayout
StaticLayout(CharSequence source, TextPaint paint, int width, Layout.Alignment align, float spacingmult, float spacingadd, boolean includepad),其中參數里:
width 是文字區域的寬度,文字到達這個寬度后就會自動換行;
align 是文字的對齊方向;
spacingmult 是行間距的倍數,通常情況下填 1 就好;
spacingadd 是行間距的額外增加值,通常情況下填 0 就好;
includeadd 是指是否在文字上下添加額外的空間,來避免某些過高的字符的繪制出現越界
Paint 對文字繪制的輔助
設置顯示效果類
設置文字大小。
設置字體。setTypeface(Typeface typeface)
是否使用偽粗體。setFakeBoldText(boolean fakeBoldText)
是否加刪除線。setStrikeThruText(boolean strikeThruText)
是否加下劃線。setUnderlineText(boolean underlineText)
設置文字橫向錯切角度。setTextSkewX(float skewX)
設置文字橫向放縮。setTextScaleX(float scaleX)
設置字符間距。setLetterSpacing(float letterSpacing)
用 CSS 的 font-feature-settings 的方式來設置文字。setFontFeatureSettings(String settings)
設置文字的對齊方式。setTextAlign(Paint.Align align)
設置繪制所使用的 Locale。setTextLocale(Locale locale) / setTextLocales(LocaleList locales)
設置是否啟用字體的 hinting (字體微調)setHinting(int mode)
設置是否開啟文字的 elegant height 。setElegantTextHeight(boolean elegant)
是否開啟次像素級的抗鋸齒( sub-pixel anti-aliasing )。setSubpixelText(boolean subpixelText)
setLinearText(boolean linearText)
測量文字尺寸類
獲取推薦的行距。
float getFontSpacing()
獲取 Paint 的 FontMetrics。
FontMetircs getFontMetrics()
獲取文字的顯示范圍。
getTextBounds(String text, int start, int end, Rect bounds)
測量文字的寬度并返回。 float measureText(String text)
獲取字符串中每個字符的寬度,并把結果填入參數 widths。getTextWidths(String text, float[] widths)
這個方法也是用來測量文字寬度的。
int breakText(String text, boolean measureForwards, float maxWidth, float[] measuredWidth)
光標相關
計算出某個字符處光標的 x 坐標。
getRunAdvance(CharSequence text, int start, int end, int contextStart, int contextEnd, boolean isRtl, int offset)
給出一個位置的像素值,計算出文字中最接近這個位置的字符偏移量
getOffsetForAdvance(CharSequence text, int start, int end, int contextStart, int contextEnd, boolean isRtl, float advance)
檢查指定的字符串中是否是一個單獨的字形 (glyph)hasGlyph(String string)