gpt4 book ai didi

android - 在 Android Canvas 上,如何使用 drawText 调整跟踪、字母间距?

转载 作者:行者123 更新时间:2023-11-29 15:06:58 25 4
gpt4 key购买 nike

当我使用 canvas.drawText() 直接在 Canvas 上绘制文本时,如何调整跟踪?

最佳答案

从 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;
}

关于android - 在 Android Canvas 上,如何使用 drawText 调整跟踪、字母间距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36244559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com