在特定字体中确定字符串的宽度

8
有没有办法确定某个字体下某个字符串有多少个像素宽度?
在我的活动中,有一些动态的字符串放在按钮上。有时候,字符串太长了,会分成两行,这让按钮看起来很丑。然而,由于我没有使用控制台字体,每个单个字符的宽度可能会有所不同。因此,写像这样的东西是没有帮助的:
String test = "someString";
if(someString.length()>/*someValue*/){
    // decrement Font size
}

因为"mmmmmmmm"比"iiiiiiii"更宽。

或者,在Android中有没有一种方法可以将某个String适合单行显示,这样系统就会自动"缩放"Font大小?

编辑:

由于wsanville的答案非常好,这是我动态设置字体大小的代码:

private void setupButton(){
    Button button = new Button();
    button.setText(getButtonText()); // getButtonText() is a custom method which returns me a certain String
    Paint paint = button.getPaint();
    float t = 0;
    if(paint.measureText(button.getText().toString())>323.0){ //323.0 is the max width fitting in the button
    t = getAppropriateTextSize(button);
    button.setTextSize(t);
    }
}

private float getAppropriateTextSize(Button button){
    float textSize = 0;
    Paint paint = button.getPaint();
    textSize = paint.getTextSize();
    while(paint.measureText(button.getText().toString())>323.0){
        textSize -= 0.25;
        button.setTextSize(textSize);
    }
    return textSize;
}
1个回答

4

感谢您提供非常有用的提示,可以在原始答案中查看我的解决方案。 - Valentino Ru

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接