111 lines
3.3 KiB
C#
Raw Permalink Normal View History

2025-01-02 12:15:45 +08:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/********************************************************************************
*Create By CG
*Function <EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͼƬ
*********************************************************************************/
namespace ZXK.UTility
{
[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);
}
}
// <20><>isX<73><58>false<73><65><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA>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
}
}
}