Unity UGUI text缩放效果实现
程序员文章站
2022-04-21 13:17:09
...
使用ugui text的时候,发现没有ngui label的shrink属性,也就是说,当text文字增多的时候,没有办法根据text的固定宽高来缩放字体的大小。这样就导致了,有些文字显示不全的情况。
我在网上找了一个很好的解决方案,详细的实现方法请看一下链接:
https://www.jianshu.com/p/45a1bb73969c
美中不足的是,它用起来虽然可以很好的控制文字的缩放,但却避免不了文字自动换行的问题,这是我们不愿意看到的,为此我再此基础上做了一些改动,先看改动部分的代码:
TextGenerationSettings settings = GetGenerationSettings(rectTransform.rect.size);
settings.resizeTextForBestFit = false;
if (!resizeTextForBestFit)
{
cachedTextGenerator.Populate(text, settings);
return;
}
int minSize = resizeTextMinSize;
int txtLen = text.Length;
for (int i = fontSize; i >= minSize; --i)
{
settings.fontSize = i;
cachedTextGenerator.Populate(text, settings);
if (cachedTextGenerator.characterCountVisible == txtLen && cachedTextGenerator.lineCount < 2) break;
}
细心的大伙会发现最后一行,我加了一个判断,当文字的行数<2(即单行text)的时候,文字就停止随fontsize继续缩小了。
我在工程上用到缩放的基本上都是单行的text,因此就把此写死了,大伙如果需要多行控制缩放,可以再次继续修改。
最后贴上完整代码,供大伙参考:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ShrinkText : Text
{
private void _UseFitSettings()
{
TextGenerationSettings settings = GetGenerationSettings(rectTransform.rect.size);
settings.resizeTextForBestFit = false;
if (!resizeTextForBestFit)
{
cachedTextGenerator.Populate(text, settings);
return;
}
int minSize = resizeTextMinSize;
int txtLen = text.Length;
for (int i = fontSize; i >= minSize; --i)
{
settings.fontSize = i;
cachedTextGenerator.Populate(text, settings);
if (cachedTextGenerator.characterCountVisible == txtLen && cachedTextGenerator.lineCount < 2) break;
}
}
private readonly UIVertex[] _tmpVerts = new UIVertex[4];
protected override void OnPopulateMesh(VertexHelper toFill)
{
if (null == font) return;
m_DisableFontTextureRebuiltCallback = true;
_UseFitSettings();
Rect rect = rectTransform.rect;
Vector2 textAnchorPivot = GetTextAnchorPivot(alignment);
Vector2 zero = Vector2.zero;
zero.x = Mathf.Lerp(rect.xMin, rect.xMax, textAnchorPivot.x);
zero.y = Mathf.Lerp(rect.yMin, rect.yMax, textAnchorPivot.y);
Vector2 vector2 = PixelAdjustPoint(zero) - zero;
IList<UIVertex> verts = cachedTextGenerator.verts;
float num1 = 1f / pixelsPerUnit;
int num2 = verts.Count - 4;
toFill.Clear();
if (vector2 != Vector2.zero)
{
for (int index1 = 0; index1 < num2; ++index1)
{
int index2 = index1 & 3;
_tmpVerts[index2] = verts[index1];
_tmpVerts[index2].position *= num1;
_tmpVerts[index2].position.x += vector2.x;
_tmpVerts[index2].position.y += vector2.y;
if (index2 == 3)
toFill.AddUIVertexQuad(this._tmpVerts);
}
}
else
{
for (int index1 = 0; index1 < num2; ++index1)
{
int index2 = index1 & 3;
_tmpVerts[index2] = verts[index1];
_tmpVerts[index2].position *= num1;
if (index2 == 3)
toFill.AddUIVertexQuad(_tmpVerts);
}
}
m_DisableFontTextureRebuiltCallback = false;
}
}
上一篇: 【quickhybrid】架构一个Hybrid框架(四)
下一篇: subline text3安装