博客迁移
个人博客站点,欢迎访问,www.jiingfengji.tech
UGUI之Text对齐至格子
背景:前几天有个需求:玩家输入的6位房间ID号,要对齐至背景格子图中,故将前面写的调整Text字间距勉强给boss用了
大致效果如图:
具体脚本代码如下:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
using System.Collections.Generic;
[AddComponentMenu("UI/Effects/TextAlignToGrid")]
public class TextAlignToGrid : BaseMeshEffect
{
public RectTransform _gridBg; //格子背景
public int _gridNum; //我的格子数为6
private Vector2 _gridSize; //格子大小
private Vector3[] _targetFocusPos; //目标中心点,也就是对应的格子中心点
public override void ModifyMesh(VertexHelper vh)
{
if (!IsActive() || vh.currentVertCount == 0)
{
return;
}
if (_gridBg == null)
{
Debug.Log("Missing Grid Background");
return;
}
Text text = GetComponent<Text>();
if (text == null)
{
Debug.Log("Missing Text component");
return;
}
_gridSize = _gridBg.sizeDelta;
int textLen = text.text.Length;
Vector3[] textFocusPos = new Vector3[textLen];
List<UIVertex> vertexs = new List<UIVertex>();
_targetFocusPos = new Vector3[textLen];
vh.GetUIVertexStream(vertexs);
//计算text各文字中心点坐标
for (int i = 0; i < textLen; i++)
{
float x = (vertexs[i * 6].position.x + vertexs[i * 6 + 1].position.x) / 2;
float y = (vertexs[i * 6 + 1].position.y + vertexs[i * 6 + 2].position.y) / 2;
textFocusPos[i] = new Vector3(x, y, 0);
}
//根据格子大小_gridSize计算目标中心点
float xOffset = _gridSize.x / _gridNum;
for (int i = 0; i < textLen; i++)
{
float x = (float)(-_gridSize.x / 2 + xOffset * (i + 0.5));
_targetFocusPos[i] = new Vector3(x, 0, 0);
}
//计算text各顶点新坐标
UIVertex v = new UIVertex();
for (int i = 0; i < vh.currentVertCount; i++)
{
vh.PopulateUIVertex(ref v, i);
float x = v.position.x + _targetFocusPos[i / 4].x - textFocusPos[i / 4].x;
float y = v.position.y + _targetFocusPos[i / 4].y - textFocusPos[i / 4].y;
v.position = new Vector3(x, y, 0);
vh.SetUIVertex(v, i);
}
}
}