【发布时间】: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;
}
【问题讨论】: