我在摆动环境中在java中实现自动换行时遇到问题。我有像素的硬限制,我不能过去。我觉得我很亲密,因为我找到了一个包装的解决方案,但它让最后一个字超过限制,然后再转到下一行。
'ni'是一个缓冲的图像,这一切都被吸引到了。
'theSettings'自定义类,包含文本的变量。
'theText'是需要包装的字符串。
这是传递给方法的内容:
FontMetrics fm = ni.createGraphics().getFontMetrics(theSettings.getFont());
//Get pixel width of string and divide by # of characters in string to get estimated width of 1 character
int charPixelWidth = fm.stringWidth(theText) / theText.length();
int charWrap = theSettings.getPixelsTillWrap() / charPixelWidth;
List<String> textList = testWordWrap(theText, charWrap);
我正在使用这种方法来测试:
//Custom String Wrapper as StringUtils.wrap keeps cutting words in half
public static List<String> testWordWrap(String wrapMe, int wrapInChar) {
StringBuilder sb = new StringBuilder(wrapMe);
int count = 0;
while((count = sb.indexOf(" ", count + wrapInChar)) != -1) {
sb.replace(count, count + 1, "\n");
}
String toArray = sb.toString();
String[] returnArray = toArray.split("\\n");
ArrayList<String> returnList = new ArrayList<String>();
for(String s : returnArray) {
returnList.add(s);
}
return returnList;
}
我还替换了文本中间的图像,但图像的大小正是它所替换的文本的大小;所以这应该不是问题。蓝线是边界框,显示包裹应该结束的位置。它表明文本继续绘制。我需要函数将'succeeded'包装到下一行;因为在任何情况下包裹都无法运行。
编辑:图像的数组运行为.toString();
[决议:+ | FT |如果你成功了,并匹配| EA |]
[任何:+ | MT |当你获得任何数字时,| QT |]
我能够找到答案。我将字符串拆分为空格,然后尝试一次添加一个字。如果太长,请跳到下一行。在这里,它被评论为帮助其他人解决同样的问题。干杯!
//@Author Hawox
//split string at spaces
//for loop checking to see if adding that next word moves it over the limit, if so go to next line; repeat
public static List<String> wordWrapCustom(String wrapMe, FontMetrics fm, int wrapInPixels){
//Cut the string into bits at the spaces
String[] split = wrapMe.split(" ");
ArrayList<String> lines = new ArrayList<String>(); //we will return this, each item is a line
String currentLine = ""; //All contents of the currentline
for(String s : split) {
//Try to add the next string
if( fm.stringWidth(currentLine + " " + s) >= wrapInPixels ) {
//Too big
if(currentLine != "") { //If it is still bigger with an empty string, still add at least 1 word
lines.add(currentLine); //Add the line without this string
currentLine = s; //Start next line with this string in it
continue;
}
}
//Still have room, or a single word that is too big
//add a space if not the first word
if(currentLine != "")
currentLine = currentLine + " ";
//Append string to line
currentLine = currentLine + s;
}
//The last line still may need to get added
if(currentLine != "") //<- Should not get called, but just in case
lines.add(currentLine);
return lines;
}