How to adjust text kerning in Android TextView?

后端 未结 12 1616
醉话见心
醉话见心 2020-11-30 20:20

Is there a way to adjust the spacing between characters in an Android TextView? I believe this is typically called \"kerning\".

I\'m aware of the

12条回答
  •  孤街浪徒
    2020-11-30 21:05

    If anyone is looking for a simple way to apply the kerning to any string (technically, CharSequence) without using a TextView:

    public static Spannable applyKerning(CharSequence src, float kerning)
    {
        if (src == null) return null;
        final int srcLength = src.length();
        if (srcLength < 2) return src instanceof Spannable
                                  ? (Spannable)src
                                  : new SpannableString(src);
    
        final String nonBreakingSpace = "\u00A0";
        final SpannableStringBuilder builder = src instanceof SpannableStringBuilder
                                               ? (SpannableStringBuilder)src
                                               : new SpannableStringBuilder(src);
        for (int i = src.length() - 1; i >= 1; i--)
        {
            builder.insert(i, nonBreakingSpace);
            builder.setSpan(new ScaleXSpan(kerning), i, i + 1,
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    
        return builder;
    }
    

提交回复
热议问题