用Unity2017 + UGUI开发游戏的时候,我们需要实现一些功能。
在NGUI下,我们很容易就可以实现,因为在NGUI里有提供大量工具。在UGUI里没有提供这些工具怎么办?
没有就自己写呗!当然如果网上有现成的代码,我们拿来就可以用!
下面给大家分享一段 UGUI字体渐变的源码
using System.Collections.Generic;
public enum Type
{
Horizontal,
Vertical
}
public enum Blend
{
Override,
Add,
Multiply
}
namespace UnityEngine.UI
{
[AddComponentMenu("UI/Effects/UGUI_Gradient")]
public class Gradient : BaseMeshEffect
{
[SerializeField]
Type _gradientType;
[SerializeField]
Blend _blendMode = Blend.Multiply;
[SerializeField]
[Range(-1, 1)]
float _offset = 0f;
[SerializeField]
UnityEngine.Gradient _effectGradient = new UnityEngine.Gradient()
{ colorKeys = new GradientColorKey[] { new GradientColorKey(Color.black, 0), new GradientColorKey(Color.white, 1) } };
#region Properties
public Blend BlendMode
{
get { return _blendMode; }
set { _blendMode = value; }
}
public UnityEngine.Gradient EffectGradient
{
get { return _effectGradient; }
set { _effectGradient = value; }
}
public Type GradientType
{
get { return _gradientType; }
set { _gradientType = value; }
}
public float Offset
{
get { return _offset; }
set { _offset = value; }
}
#endregion
public override void ModifyMesh(VertexHelper helper)
{
if (!IsActive() || helper.currentVertCount == 0)
return;
List<UIVertex> _vertexList = new List<UIVertex>();
helper.GetUIVertexStream(_vertexList);
int nCount = _vertexList.Count;
switch (GradientType)
{
case Type.Horizontal:
{
float left = _vertexList[0].position.x;
float right = _vertexList[0].position.x;
float x = 0f;
for (int i = nCount - 1; i >= 1; --i)
{
x = _vertexList[i].position.x;
if (x > right) right = x;
else if (x < left) left = x;
}
float width = 1f / (right - left);
UIVertex vertex = new UIVertex();
for (int i = 0; i < helper.currentVertCount; i++)
{
helper.PopulateUIVertex(ref vertex, i);
vertex.color = BlendColor(vertex.color, EffectGradient.Evaluate((vertex.position.x - left) * width - Offset));
helper.SetUIVertex(vertex, i);
}
}
break;
case Type.Vertical:
{
float bottom = _vertexList[0].position.y;
float top = _vertexList[0].position.y;
float y = 0f;
for (int i = nCount - 1; i >= 1; --i)
{
y = _vertexList[i].position.y;
if (y > top) top = y;
else if (y < bottom) bottom = y;
}
float height = 1f / (top - bottom);
UIVertex vertex = new UIVertex();
for (int i = 0; i < helper.currentVertCount; i++)
{
helper.PopulateUIVertex(ref vertex, i);
vertex.color = BlendColor(vertex.color, EffectGradient.Evaluate((vertex.position.y - bottom) * height - Offset));
helper.SetUIVertex(vertex, i);
}
}
break;
}
}
Color BlendColor(Color colorA, Color colorB)
{
switch (BlendMode)
{
default: return colorB;
case Blend.Add: return colorA + colorB;
case Blend.Multiply: return colorA * colorB;
}
}
}
}
这个可以水平,垂直渐变 颜色可以叠加 看代码就知道了。
如果你觉得你的方法比这个更好,欢迎留言讨论。
感兴趣的朋友可以加群一起讨论,扫二维码加群
王银太一,王银太二
微信 QQ:1160364001