2016-03-27 9 views

cevap

2

Lollipop'ten bu yana, setLetterSpacing yöntemi Paint'te kullanılabilir. Bu yaklaşım benim için çalıştı:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { 
    paint.setLetterSpacing(-0.04f); // setLetterSpacing is only available from LOLLIPOP and on 
    canvas.drawText(text, xOffset, yOffset, paint); 
} else { 
    float spacePercentage = 0.05f; 
    drawKernedText(canvas, text, xOffset, yOffset, paint, spacePercentage); 
} 


/** 
* Draw kerned text by drawing the text string character by character with a space in between. 
* Return the width of the text. 
* If canvas is null, the text won't be drawn, but the width will still be returned/ 
* kernPercentage determines the space between each letter. If it's 0, there will be no space between letters. 
* Otherwise, there will be space between each letter. The value is a fraction of the width of a blank space. 
*/ 
private int drawKernedText(Canvas canvas, String text, float xOffset, float yOffset, Paint paint, float kernPercentage) { 
    Rect textRect = new Rect(); 
    int width = 0; 
    int space = Math.round(paint.measureText(" ") * kernPercentage); 
    for (int i = 0; i < text.length(); i++) { 
     if (canvas != null) { 
      canvas.drawText(String.valueOf(text.charAt(i)), xOffset, yOffset, paint); 
     } 
     int charWidth; 
     if (text.charAt(i) == ' ') { 
      charWidth = Math.round(paint.measureText(String.valueOf(text.charAt(i)))) + space; 
     } else { 
      paint.getTextBounds(text, i, i + 1, textRect); 
      charWidth = textRect.width() + space; 
     } 
     xOffset += charWidth; 
     width += charWidth; 
    } 
    return width; 
} 
İlgili konular