其他分享
首页 > 其他分享> > 用BaseMeshEffect实现的渐变

用BaseMeshEffect实现的渐变

作者:互联网

原理就是按点的位置占长宽的百分比算出颜色

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using System;
/// <summary>
/// 渐变字体
/// </summary>
[AddComponentMenu("UI/Effects/Gradient")]
public class FontGradient : BaseMeshEffect
{
public Gradient useColor;
[Range(0,1)]
public float angle;
private RectTransform transImg
{
get
{
return transform as RectTransform;
}
}
public override void ModifyMesh(VertexHelper vh)
{
if (!IsActive())
{
return;
}

var count = vh.currentVertCount;
if (count == 0)
return;

var vertexs = new List<UIVertex>();
for (var i = 0; i < count; i++)
{
var vertex = new UIVertex();
vh.PopulateUIVertex(ref vertex, i);
vertexs.Add(vertex);
}

//var topY = vertexs[0].position.y;
//var bottomY = vertexs[0].position.y;
//var leftX = vertexs[0].position.x;
//var rightX = vertexs[0].position.x;

//for (var i = 1; i < count; i++)
//{
// var y = vertexs[i].position.y;
// if (y > topY)
// topY = y;
// else if (y < bottomY)
// bottomY = y;
// var x = vertexs[i].position.x;
// if (x > rightX)
// rightX = x;
// else if (x < leftX)
// leftX = x;
//}

var height = transImg.rect.height;
var width = transImg.rect.width;
//Vector2 center = new Vector2((leftX + rightX) * 0.5f, (bottomY + topY) * 0.5f);

for (var i = 0; i < count; i++)
{
var vertex = vertexs[i];
//if (usecenter)
//center = new Vector2(vertex.position.x * 0.5f, vertex.position.y * 0.5f);
//Vector2 a = new Vector2(vertex.position.x, vertex.position.y) - center;
//Vector2 r = new Vector2(Mathf.Sin((angle + 90) / 180 * Mathf.PI), Mathf.Cos((angle + 90) / 180 * Mathf.PI));
//float check = Vector2.Dot(a.normalized, r) * 0.5f + 0.5f;
//float x = Mathf.InverseLerp(leftX, rightX, vertex.position.x);
//float y = Mathf.InverseLerp(bottomY, topY, vertex.position.y);
float x = (vertex.position.x + width / 2) / width;
float y = (vertex.position.y + height / 2) / height;
float check = Mathf.Lerp(x, y, angle);
Color color = useColor.Evaluate(check);
vertex.color = graphic.color * color;
vh.SetUIVertex(vertex, i);
}
//NDebug.Log("check");
}
}

标签:实现,渐变,vertex,Mathf,position,var,BaseMeshEffect,vertexs,Vector2
来源: https://www.cnblogs.com/mcyushao/p/15296675.html