用法
image.png将颜色渐变组件挂在Text所属GameObject上。(若有描边、阴影等组件,为了使这些组件的功能仍起效,需让颜色渐变组件在这些组件之上)
颜色渐变组件 可设置如下参数
- 渐变方向:竖直 或 水平
- 颜色叠加模式:覆盖、相加、相乘
- 渐变偏移
-
渐变色
image.png
颜色渐变组件 代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEngine.UI
{
[AddComponentMenu("UI/Effects/Gradient")]
public class UiGradient : BaseMeshEffect
{
[SerializeField]
private DirType _dir = DirType.Vertical;
[SerializeField]
private BlendType _blend = BlendType.Override;
[SerializeField, Range(-1, 1)]
private float _offset = 0f;
[SerializeField]
private Gradient _gradient = new Gradient(){ colorKeys = new GradientColorKey[] { new GradientColorKey(Color.black, 0), new GradientColorKey(Color.white, 1) } };
public override void ModifyMesh(VertexHelper vh)
{
if (!IsActive() || vh.currentVertCount == 0)
{
return;
}
var vertexs = new List<UIVertex>();
vh.GetUIVertexStream(vertexs);
bool isX = true;
switch (_dir)
{
case DirType.Horizontal:
isX = true;
break;
case DirType.Vertical:
isX = false;
break;
default:
break;
}
var inverseLength = GetInverseLength(vertexs, isX, out float min, out float max);
var vertex = new UIVertex();
for (int i = 0; i < vh.currentVertCount; i++)
{
vh.PopulateUIVertex(ref vertex, i);
vertex.color = BlendColor(vertex.color, _gradient.Evaluate((isX ? (vertex.position.x - min): (vertex.position.y - min)) * inverseLength - _offset), _blend);
vh.SetUIVertex(vertex, i);
}
}
// 若isX是false,则认为是y
private float GetInverseLength(List<UIVertex> vertexs, bool isX, out float min, out float max)
{
float inverseLength = 0;
min = isX ? vertexs[0].position.x : vertexs[0].position.y;
max = min;
for (int i = 1; i < vertexs.Count; i++)
{
var temp = isX ? vertexs[i].position.x : vertexs[i].position.y;
if (temp > max)
{
max = temp;
}
else if (temp < min)
{
min = temp;
}
}
inverseLength = 1 / (max - min);
return inverseLength;
}
private Color BlendColor(Color originalColor, Color newColor, BlendType blendType)
{
var ret = newColor;
switch (blendType)
{
case BlendType.Override: ret = newColor; break;
case BlendType.Add: ret = originalColor + newColor; break;
case BlendType.Multiply: ret = originalColor * newColor; break;
default:break;
}
return ret;
}
private enum DirType
{
None,
Horizontal,
Vertical,
}
private enum BlendType
{
None,
Override,
Add,
Multiply
}
}
}
网友评论