当我使用canvas.drawText()
直接在画布上绘制文本时,如何调整跟踪?
问问题
2299 次
1 回答
6
从 Lollipop 开始,方法 setLetterSpacing 在 Paint 上可用。这种方法对我有用:
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;
}
于 2016-03-27T06:32:39.790 回答