Java split string at certain length in pixels

时间:2019-04-08 13:58:02

标签: java string graphics split pixel

I need to split a String that is going to be displayed in a box using java.awt.Graphics. The problem is, I need the string to automatically be split when it reaches the rectangles width in pixels. For example,

"This is an example string. What goes into the string does not matter" 
[----------------------------------------] <-- Hypothetical width of box/rect

I need the string to be split between "goes" and "into" so I can then have the rest of the text on a new line:

"This is an example string. What goes
into the string does not matter" 
[----------------------------------------] <-- Hypothetical width of box/rect

I know how to get the width of a string, but I do not know how to go about splitting it.

1 个答案:

答案 0 :(得分:0)

我知道我要说出是否想出来太迟了,但是我自己没有第3方API就设法做到了。好像字符串长度太长,最后一个单词被切断,效率不是很高。 (您可以根据需要查看代码,但是由于很长一段时间都没有看过,所以我无法再解释它的工作原理。

public class ConsoleLog {
private static Color c = Color.WHITE;
public static Color getC() {
    return c;
}

public static void setC(Color c) {
    ConsoleLog.c = c;
}

private static int pos;
private static List<String[]> logs;
private static List<Point>linesPos = new ArrayList<Point>();
private static Rectangle r = Main.Main.screenSize;
public static void log(List <String[]> logs, Graphics g) {
    g.setColor(c);
    ConsoleLog.logs = logs;
    splitConsole(g);
}

public static void splitConsole(Graphics g){
    pos = 0;
    for(int i = 0; i < (r.height / 2) / 10 - 10; i++) {
        linesPos.add(new Point(10, (i * (r.height / (50 + 3) + 5) + 15)));
    }
    for(int i = 0; i < logs.size(); i++) {
        for(int ie = 0; ie < logs.get(i).length || pos < logs.get(i).length; ie++) {
            g.drawString(logs.get(i)[ie], linesPos.get(pos).x, linesPos.get(pos).y);
            pos++;
        }
    }
}

很明显,我正在开发一个小型游戏引擎,并决定将其废弃,因为它变得过于混乱,效率低下,并且是围绕Clicker游戏构建的。我正在开发第二款游戏,它将能够创建用户想要的任何2D游戏,而且它非常人性化。它几乎可以为它的第一个版本准备好了,我很高兴看到可以用它来制作!