How to adjust text kerning in Android TextView?

后端 未结 12 1606
醉话见心
醉话见心 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:07

    I wanted to use @PedroBarros answer, but by defining what the spacing should be in pixel.

    Here's my edit to the applySpacing method :

    private void applySpacing() {
        if (this == null || this.originalText == null) return;
    
        Paint testPaint = new Paint();
        testPaint.set(this.getPaint());
        float spaceOriginalSize = testPaint.measureText("\u00A0");
        float spaceScaleXFactor = ( spaceOriginalSize > 0 ? spacing/spaceOriginalSize : 1);
    
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < originalText.length(); i++) {
            builder.append(originalText.charAt(i));
            if(i+1 < originalText.length()) {
                builder.append("\u00A0");
            }
        }
        SpannableString finalText = new SpannableString(builder.toString());
        if(builder.toString().length() > 1) {
            for(int i = 1; i < builder.toString().length(); i+=2) {
                finalText.setSpan(new ScaleXSpan(spaceScaleXFactor), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        super.setText(finalText, BufferType.SPANNABLE);
    }
    

    I'm a beginner as an Android developer, please feel free to let me know if this is not good !

提交回复
热议问题