全理由与Java Graphics.drawString更换?理由、Java、drawString、Graphics

由网友(踏平女宿舍)分享简介:有谁知道现有的code,可以让你在Java2D的画完全对齐文本?Does anyone know of existing code that lets you draw fully justified text in Java2D?例如,如果我说,束带(在此示例文本,X,Y,宽度),是有一个现有的库,可以计算出有多...

有谁知道现有的code,可以让你在Java2D的画完全对齐文本?

Does anyone know of existing code that lets you draw fully justified text in Java2D?

例如,如果我说,束带(在此示例文本,X,Y,宽度),是有一个现有的库,可以计算出有多少宽度内的文本适合,做一些字符间距,使文本看起来很好,并自动执行基本的自动换行?

For example, if I said, drawString("sample text here", x, y, width), is there an existing library that could figure out how much of that text fits within the width, do some inter-character spacing to make the text look good, and automatically do basic word wrapping?

推荐答案

虽然不是最优雅的,也没有强大的解决方案,这里,将采取的 字体 当前的 图形 对象并获取其的 的FontMetrics ,以找出绘制文本,并在必要时,移动到一个新的行:

Although not the most elegant nor robust solution, here's an method that will take the Font of the current Graphics object and obtain its FontMetrics in order to find out where to draw the text, and if necessary, move to a new line:

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 位置。

This implementation will separate the given String into an array of String by using the split method with a space character as the only word separator, so it's probably not very robust. It also assumes that the word is followed by a space character and acts accordingly when moving the curX position.

我不建议使用此实现,如果我是你,但可能需要为了使另一个实现仍然使用由的 的FontMetrics 类。

I wouldn't recommend using this implementation if I were you, but probably the functions that are needed in order to make another implementation would still use the methods provided by the FontMetrics class.

阅读全文

相关推荐

最新文章