Android:Paint.breakText(...) 不准确吗?

发布于 2024-10-19 04:16:57 字数 970 浏览 2 评论 0原文

我有一个视图,它绘制一个矩形,其中包含一行文本。视图使用分隔文本来确保没有文本延伸到矩形之外;它会忽略任何这样做的文本。这对于某些字符来说效果很好,但通常由“l”和“f”组成的字符串会延伸到矩形之外。所以,我需要在这里进行健全性检查:下面的代码是否存在一些明显的缺陷,或者 Paint.breakText(...) 是否可能不准确?

public void onDraw(Canvas canvas)
{
    int MARGIN = 1;
    int BORDER_WIDTH = 1;

    Paint p = new Paint();
    p.setAntiAlias(true);
    p.setTextSize(12);
    p.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL));

    RectF rect = getRect();

    float maxWidth = rect.width() - MARGIN - BORDER_WIDTH * 2;

    String str = getText();
    char[] chars = str.toCharArray();
    int nextPos = p.breakText(chars, 0, chars.length, maxWidth, null);
    str = str.substring(0, nextPos);

    float textX = MARGIN + BORDER_WIDTH;
    float textY = (float) (Math.abs(p.getFontMetrics().ascent) + BORDER_WIDTH + MARGIN);

    canvas.drawText(str, textX, textY, p);

    p.setStrokeWidth(BORDER_WIDTH);
    p.setStyle(Style.STROKE);

    canvas.drawRect(rect, p);
}

I have a View which draws a rectangle with a line of text inside of it. The view uses break text to ensure that no text extends outside of the rectangle; it ignores any text that does. This works fine for some characters, but often Strings made up of 'l's and 'f's extend outside of the rectangle. So, I'm in need of a sanity check here: Is there some obvious flaw in my below code, or is it possible that Paint.breakText(...) is inaccurate?

public void onDraw(Canvas canvas)
{
    int MARGIN = 1;
    int BORDER_WIDTH = 1;

    Paint p = new Paint();
    p.setAntiAlias(true);
    p.setTextSize(12);
    p.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL));

    RectF rect = getRect();

    float maxWidth = rect.width() - MARGIN - BORDER_WIDTH * 2;

    String str = getText();
    char[] chars = str.toCharArray();
    int nextPos = p.breakText(chars, 0, chars.length, maxWidth, null);
    str = str.substring(0, nextPos);

    float textX = MARGIN + BORDER_WIDTH;
    float textY = (float) (Math.abs(p.getFontMetrics().ascent) + BORDER_WIDTH + MARGIN);

    canvas.drawText(str, textX, textY, p);

    p.setStrokeWidth(BORDER_WIDTH);
    p.setStyle(Style.STROKE);

    canvas.drawRect(rect, p);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

自由如风 2024-10-26 04:16:57

这是通过以下方法修复的:Paint.setSubpixelText(true);

This was fixed by: Paint.setSubpixelText(true);

分分钟 2024-10-26 04:16:57

问题可能是你如何绘制矩形。笔划不在矩形之外,笔划的一半在内部,一半在外部。

The problem might be how you draw your rectangle. Strokes are not outside of the rectangle, half of the stroke is inside, half is outside.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文