您的位置:首页 > 移动开发 > Unity3D

Unity5的uGUI中实现文字渐变效果(Gradient)

2015-12-03 11:23 471 查看
代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[AddComponentMenu("UI/Effects/Gradient")]
public class Gradient : BaseMeshEffect
{
[SerializeField] private Color32 topColor = Color.white;

[SerializeField] private Color32 bottomColor = Color.black;

public override void ModifyMesh(VertexHelper vh)
{
if (!IsActive()) {
return;
}

var vertexList = new List<UIVertex>();
vh.GetUIVertexStream(vertexList);
int count = vertexList.Count;

ApplyGradient(vertexList, 0, count);
vh.Clear();
vh.AddUIVertexTriangleStream(vertexList);
}

private void ApplyGradient(List<UIVertex> vertexList, int start, int end)
{
float bottomY = vertexList[0].position.y;
float topY = vertexList[0].position.y;
for (int i = start; i < end; ++i) {
float y = vertexList[i].position.y;
if (y > topY) {
topY = y;
} else if (y < bottomY) {
bottomY = y;
}
}

float uiElementHeight = topY - bottomY;
for (int i = start; i < end; ++i) {
UIVertex uiVertex = vertexList[i];
uiVertex.color = Color32.Lerp(bottomColor, topColor, (uiVertex.position.y - bottomY)/uiElementHeight);
vertexList[i] = uiVertex;
}
}
}

主要参考了雨凇的文章和其下的回复。  这里额外说明一个关键点就是Unity的uGUI的特殊效果的处理都是基于顶点的,它并不是专门为字体写一个阴影、描边、渐变的处理,而是用顶点的处理模拟了其效果。所以如果文字同时有阴影(描边)和渐变的时候,要注意脚本的添加顺序。应该先添加渐变的脚本,然后再添加描边的脚本,否则按照代码逻辑来处理,渐变的顶点处理会把描边的顶点颜色也都给修改了,也就是说没有描边效果了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: