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

标签 android canvas text drawtext kerning

当我使用 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/

相关文章:

android - 未找到处理 Intent 的 Activity ?

javascript - 将 HTML 绘制到 Canvas

iOS。方法 adjustsFontSizeToFitWidth 不能正常工作

php - 如何使用 php 搜索文本 if ($text contains "World")

css - float div 中的文本

android - Genymotion Android 模拟器 - adb 访问?

java - Android 开机接收器崩溃

android - 如何在 KSOAP2 中将 transport.dump 大小从 256 字节增加到 512 或更多字节?

javascript - JS 中 DeltaTime 函数的不稳定结果

javascript - 如何优化大 Canvas 动画