全理由与Java Graphics.drawString更换? [英] Full-justification with a Java Graphics.drawString replacement?

查看:174
本文介绍了全理由与Java Graphics.drawString更换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道现有的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;
	}
}

本实施将单独给定的字符串字符串阵列使用<一个href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)"><$c$c>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.

这篇关于全理由与Java Graphics.drawString更换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆