有没有办法弄清楚某个Font中某个String的宽度是多少?
在我的Activity中,有一个按钮上的动态字符串.有时,字符串太长而且分为两行,这使得Button看起来很难看.但是,由于我没有使用某种控制台字体,因此单个字符宽度可能会有所不同.所以写这样的东西并不是一种帮助
String test = "someString";
if(someString.length()>/*someValue*/){
// decrement Font size
}
因为“mmmmmmmm”比“iiiiiiii”宽.
或者,Android中是否有一种方法可以在一条线上拟合某个字符串,因此系统会自动“缩放”字体大小?
编辑:
既然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;
}