【问题标题】:Figure out width of a String in a certain Font找出某个字体中字符串的宽度
【发布时间】:2012-10-30 13:59:05
【问题描述】:

有什么方法可以计算出某个String 在某个Font 中有多少像素宽?

在我的Activity,有动态的Strings 换上了Button。有时,String 太长,分成两行,是什么让Button 看起来很丑。但是,由于我不使用某种控制台Font,因此单个字符宽度可能会有所不同。所以写这样的东西没有帮助

String test = "someString";
if(someString.length()>/*someValue*/){
    // decrement Font size
}

因为“mmmmmmmm”比“iiiiiiiii”宽。

或者,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;
}

【问题讨论】:

    标签: java android string fonts


    【解决方案1】:

    您应该可以使用Paint.setTypeface(),然后使用Paint.measureText()。您还可以在 Paint 类上找到其他方法,例如 setTextSize()

    this question 解决了您关于缩放文本的后续问题。

    【讨论】:

    • 感谢您提供非常有用的提示,请在原始答案中查看我的解决方案
    猜你喜欢
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2014-09-04
    • 2020-12-09
    • 1970-01-01
    相关资源
    最近更新 更多