Created
June 4, 2013 07:24
-
-
Save kyuuki/5704195 to your computer and use it in GitHub Desktop.
Android でテキストが 1 行に収まるように調整。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* TextView のテキストサイズを 1 行に収まるように調整。 | |
* | |
* https://gist.github.com/STAR-ZERO/2934490 を参考にした | |
*/ | |
public static float resizeTextView(TextView textView, float minTextSize) { | |
float textSize = getAdjustTextSize(textView.getWidth(), textView.getText().toString(), | |
textView.getTextSize(), minTextSize); | |
// テキストサイズ設定 (setTextSize はデフォルトで sp 指定なので TypedValue.COMPLEX_UNIT_PX を指定すること!) | |
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); | |
return textSize; | |
} | |
/** | |
* 指定された幅に収まるようなテキストサイズを取得。 | |
* | |
* - 全体的にピクセル単位 (sp ではない) なので注意! | |
* | |
* @param width 収めたい幅 (px) | |
* @param text 入れたいテキスト | |
* @param initTextSize テキストサイズ初期値 (この値からはじめて徐々に小さくしていく) (px) | |
* @param minTextSize 最小テキストサイズ (このサイズよりは小さくしない) (px) | |
* | |
* @return 収まるテキストサイズ (px) | |
*/ | |
public static float getAdjustTextSize(int width, String text, float initTextSize, | |
float minTextSize) { | |
Paint paint = new Paint(); | |
float textWidth; | |
// テキストサイズ (この値を徐々に小さくしていく) | |
float textSize = initTextSize; | |
// Paint にテキストを書いてテキスト横幅取得 | |
paint.setTextSize(textSize); | |
textWidth = paint.measureText(text); | |
/* | |
* 横幅に収まるまでループ | |
*/ | |
while (width < textWidth) { | |
textSize = textSize - 1; | |
// 最小サイズ以下になっちゃったら終了 | |
if (minTextSize > 0 && minTextSize >= textSize) { | |
textSize = minTextSize; | |
break; | |
} | |
paint.setTextSize(textSize); | |
textWidth = paint.measureText(text); | |
} | |
return textSize; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment