Val*_* Ru 8 java string fonts android
有什么办法找出多少像素宽一定String在某Font是什么?
在我的Activity,有动态Strings穿上了Button.有时,String太长了,它分为两行,这Button看起来很难看.但是,由于我不使用某种控制台Font,因此单个字符宽度可能会有所不同.所以写这样的东西并不是一种帮助
String test = "someString";
if(someString.length()>/*someValue*/){
// decrement Font size
}
Run Code Online (Sandbox Code Playgroud)
因为"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;
}
Run Code Online (Sandbox Code Playgroud)
您应该能够使用Paint.setTypeface( ) ,然后使用Paint.measureText()。您还会在课程中找到其他Paint类似的方法setTextSize()来提供帮助。
您关于缩放文本的后续问题已在该问题中得到解决。