Get correct position of letters using cachedTextGe

2019-03-01 14:40发布

问题:

Consider a Text with many paragraphs of text. It's easy to find where a certain character is, using UICharInfo.

Example, find all newlines...

TextGenerator tg = text.cachedTextGenerator;
int kText = tg.characterCount;
for (int i=0; i < kText; ++i)
  {
  if ( text.text[i] == '\n' )
    Debug.Log("found a newline at " + tg.verts[i * 4].position.y);
  }

This gives the correct ratios but they are all out by some scaling factor.

It seems to depend on many things (screen shape, pixels, settings and more).

Naturally this is in a Canvas using scale-with-screen-size.

How do you get the actual offset of a character - to use in a scroll view to scroll to that point?

回答1:

It uses a combination of text.pixelsPerUnit and what they call a rounding offset. The code they use is open source and can be found here. The relevant lines you are looking for are in the function

protected override void OnPopulateMesh(VertexHelper toFill)

All the functions they use to calculate them are public and should be easy enough to duplicate on your side