UGUI之Text对齐至格子

博客迁移

个人博客站点,欢迎访问,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);
        }
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值