Skip to content

Instantly share code, notes, and snippets.

@kou-yeung kou-yeung/JustifyText.cs Secret
Created Aug 6, 2018

Embed
What would you like to do?
Unityのテキストを「両端揃え」「均等割り付け」対応
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Linq;
[RequireComponent(typeof(Text))]
public class JustifyText : UIBehaviour, IMeshModifier
{
/// <summary>
/// 両端揃え
/// </summary>
public bool bothEnds = false;
Text textComponent
{
get { return GetComponent<Text>(); }
}
float Width
{
get { return GetComponent<RectTransform>().sizeDelta.x; }
}
TextGenerator textGenerator
{
get { return textComponent.cachedTextGenerator; }
}
public void ModifyMesh(Mesh mesh)
{
}
public void ModifyMesh(VertexHelper vh)
{
List<UIVertex> v = new List<UIVertex>();
vh.GetUIVertexStream(v);
List<UIVertex> newVertex = new List<UIVertex>();
foreach (var line in GetLineInfo())
{
var vertices = v.Skip(line.start * 6).Take(line.count * 6).ToList();
if (vertices.Count <= 0) continue;
var textWidth = TextWidth(vertices);
if (Width <= textWidth) return;
var space = (Width - textWidth) / ((vertices.Count / 6) + (bothEnds ? -1 : 1));
var offset = 0f;
for (int i = (bothEnds ? 6 : 0); i < vertices.Count; i += 6)
{
offset += space;
for (int j = 0; j < 6; j++)
{
var index = i + j;
UIVertex vertex = vertices[index];
var pos = vertex.position;
pos.x += offset;
vertex.position = pos;
vertices[index] = vertex;
}
}
newVertex.AddRange(vertices);
}
vh.Clear();
vh.AddUIVertexTriangleStream(newVertex);
}
/// <summary>
/// テキストの描画幅を取得する
/// </summary>
/// <returns></returns>
private float TextWidth(List<UIVertex> verts)
{
var text = textComponent.text;
UIVertex start = verts[0];
UIVertex end = verts[verts.Count - 3];
return end.position.x - start.position.x;
}
struct LineInfo
{
public int start;
public int count;
}
List<LineInfo> GetLineInfo()
{
var lines = textGenerator.lines;
List<LineInfo> res = new List<LineInfo>(lines.Count);
for (int i = 0; i < lines.Count - 1; i++)
{
var start = lines[i].startCharIdx;
var count = (lines[i + 1].startCharIdx - 1) - start;
res.Add(new LineInfo { start = start, count = count });
}
{
var last = lines.Last();
var start = last.startCharIdx;
var count = (textGenerator.characters.Count - 1) - start;
res.Add(new LineInfo { start = start, count = count });
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.