Java Graphics.drawString置換による完全な正当化?
質問
Java2Dで完全に正当化されたテキストを描画できる既存のコードを知っている人はいますか?
たとえば、 drawString(" sample text&quot ;, x、y、width)
と言った場合、そのテキストがどれだけ収まるかを把握できる既存のライブラリがあります幅、テキストの見栄えを良くするためにいくつかの文字間スペーシングを行い、基本的なワードラッピングを自動的に行いますか?
解決
最もエレガントで堅牢なソリューションではありませんが、 Font
。 html "rel =" noreferrer "> Graphics
オブジェクトを取得し、その FontMetrics
を使用して、テキストを描画する場所を見つけ、必要に応じて新しい行に移動します。
public void drawString(Graphics g, String s, int x, int y, int width)
{
// FontMetrics gives us information about the width,
// height, etc. of the current Graphics object's Font.
FontMetrics fm = g.getFontMetrics();
int lineHeight = fm.getHeight();
int curX = x;
int curY = y;
String[] words = s.split(" ");
for (String word : words)
{
// Find out thw width of the word.
int wordWidth = fm.stringWidth(word + " ");
// If text exceeds the width, then move to next line.
if (curX + wordWidth >= x + width)
{
curY += lineHeight;
curX = x;
}
g.drawString(word, curX, curY);
// Move over to the right for next word.
curX += wordWidth;
}
}
この実装は、 split
メソッド。単語区切り文字としてスペース文字のみを使用、したがって、おそらくあまり堅牢ではありません。また、単語の後にスペース文字が続くと想定し、 curX
の位置を移動するときにそれに応じて動作します。
私がこの実装を使用することはお勧めしませんが、おそらく別の実装を作成するために必要な関数は、 FontMetrics
クラス。
他のヒント
ワードラッピングについては、グラフィックを使用して複数の行に文字列を出力する方法。ここに理由はありません。追加するのが簡単か(または不可能か)わかりません...
所属していません StackOverflow