首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Android画布上,我如何使用drawText调整跟踪,字母之间的间距?

在Android画布上,我如何使用drawText调整跟踪,字母之间的间距?
EN

Stack Overflow用户
提问于 2016-03-27 14:31:01
回答 1查看 2.3K关注 0票数 1

当我使用canvas.drawText()直接在画布上绘制文本时,我如何调整描边?

EN

回答 1

Stack Overflow用户

发布于 2016-03-27 14:32:40

从棒棒糖开始,setLetterSpacing方法在绘制中可用。这种方法对我很有效:

代码语言:javascript
复制
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;
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36244559

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档