UI Text multiline uneven alignment

2019-08-10 16:51发布

The text is a string with undefined number of words. The alignment should be something like this:

        The text is starting from here
    then when the line is over it
goes to the next line etc.

Is it possible to align text this way in Unity using UI components?

1条回答
啃猪蹄的小仙女
2楼-- · 2019-08-10 17:23

No, there's no way built-in.

Note that Unity DOES NOT offer "text length" functions - as for example iOS does.

I really cannot think of anyway at all to find out "where it wraps" a line. You could, perhaps, iterate over each character one by one growing the string one character at a time, and when the width stops increasing, you know, it has wrapped. (Get the width with .renderer.bounds.size.x )

I would probably encourage you to just have say three UI.Text and separate your string. Simply, separate the string in to say chunks of 50 characters (stopping at a space) or perhaps seven words. (They won't be exactly the same length, but it will be fine.)

NOTE

If you're a new Unity programmer or hobbyist, the usual solution to things like this is to

"USE AN ASSET!"

Someone somewhere has probably programmed what you need. So start googling for something like "free asset, wrap text around a shape" or similar. Often, it pays to email the people who make such packages, and they often know something that does what you need, if their one does not.

Example .. http://forum.unity3d.com/threads/text-box.124906/

I easily found that by googling unity3d text utility wrap around a shape


Here's some code to split a LONG line of reasonable text, in to a number of lines of length limit say 50 characters. Note that the text must be "reasonable", you can't have any ridiculously long words etc.

string wholeSentence = "Your whole sentence here ... goes on and on.";

List<string> words = new List<string>(
  wholeSentence
  .Split(new string[] { " " },
  StringSplitOptions.RemoveEmptyEntries)
  );

List<string> finalLines = new List<string>();

int count = 0;
string nextLine = "";
foreach (word w in words)
  {
  nextLine = nextLine + w + " ";
  count += w.Length;
  if (count>50)
   {
   finalLines.Add(nextLine);
   count=0;
   nextLine = "";
   }
  }

if (nextLine!="") finalLine.Add(nextLine);

that will give you all the lines, in the List "finalLines" ! Cheers

查看更多
登录 后发表回答