有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java计算呈现的文本字符串的尺寸(在呈现之前)

我想把一个字符串“强”>画布对齐在中间。如果我有这样的代码

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

String centered_text = "Hello World";

然后设置我的画作风格大小

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()不是真正的方法。所以我的想法是使用文本的大小字符串的大小来找到宽度高度。因此,大致如下:

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

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


共 (1) 个答案

  1. # 1 楼答案

    假设你在Java Swing中,你想要的是FontMetrics

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

    将返回一个包含字符串大小的矩形2D