【问题标题】:Calculating the dimensions of a rendered string of text (before rendering it)计算渲染文本字符串的尺寸(在渲染之前)
【发布时间】:2013-01-11 23:38:19
【问题描述】:

我想将 canvas 绘制的字符串完美地对齐在中间。所以如果我有这样的代码

Paint p = new Paint();
Canvas c = holder.lockCanvas();

String centered_text = "Hello World";

然后设置我的画图stylesize

p.setTextSize(35);
p.setStyle(Style.STROKE);

现在要在中间画出我的字符串

c.drawText(centered_text, c.getWidth()/2, c.getHeight()/2, p);

但这实际上不会使我的文本居中,它会将左上角置于中心。为了使其居中,我需要知道以像素而不是字符为单位的字符串字面宽度和高度。

int string_width = centered_text.getWidth(); //String.getWidth() is not a real methode
int string_height = centered_text.getHeight(); //String.getHeight() is not a real methode

c.drawText(centered_text, (c.getWidth()/2)-(string_width/2), (c.getHeight()/2)-(string_height/2), p);

这将使文本居中,但 String.getWidth()String.getHeight() 不是真正的方法。所以我的想法是使用 textsizeStringsize 来找到 宽度高度。所以有些事情是这样的:

int string_width = centered_text.length()*p.getTextSize();
int string_height = p.getTextSize();

但我觉得这是错误的,因为不同的字符大小不同......任何人都有任何想法。

【问题讨论】:

  • 不是答案,但是:是的,如果您不使用等宽字体,不同的字符将具有不同的宽度。此外,如果渲染足够先进,它可能会引入字距调整(即字体之间的可变空间)。最后,您可能不想垂直对齐到最高字母和基线的中间,而是从字体的 X-Height 到基线。
  • 你用的是什么库?在 SWT 中,你有`getStringExtent(String)。检查this tutorial

标签: java string canvas paint


【解决方案1】:

假设您使用的是 Java Swing,您想要的是 FontMetrics

new FontMetrics(canvas.getFont()).getStringBounds(someString, canvas.getGraphics());

将返回一个包含字符串大小的 Rectangle2D。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 2015-06-18
    • 1970-01-01
    相关资源
    最近更新 更多