Unity中实现UI渐变
Posted Hello Bug.
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity中实现UI渐变相关的知识,希望对你有一定的参考价值。
一:效果演示
二:使用
TopColor:顶部颜色
BottomColor:底部颜色
三:代码实现
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[DisallowMultipleComponent]
[AddComponentMenu("LFramework/UI/Effects/Gradient", 1)]
public class Gradient : BaseMeshEffect
//顶部颜色
[SerializeField]
Color32 m_TopColor = Color.white;
public Color32 TopColor
get
return m_TopColor;
set
m_TopColor = value;
graphic.SetVerticesDirty();
//底部颜色
[SerializeField]
Color32 m_BottomColor = Color.black;
public Color32 BottomColor
get
return m_BottomColor;
set
m_BottomColor = value;
graphic.SetVerticesDirty();
//顶点缓存
List<UIVertex> vertexCache = new List<UIVertex>();
public override void ModifyMesh(VertexHelper vh)
if (!IsActive())
return;
vh.GetUIVertexStream(vertexCache);
ApplyGradient(vertexCache);
vh.Clear();
vh.AddUIVertexTriangleStream(vertexCache);
vertexCache.Clear();
void ApplyGradient(List<UIVertex> vertexCache)
if (vertexCache.Count == 0)
return;
float topY = vertexCache[0].position.y;
float bottomY = vertexCache[0].position.y;
foreach (var vertex in vertexCache)
if (vertex.position.y > topY)
topY = vertex.position.y;
else if (vertex.position.y < bottomY)
bottomY = vertex.position.y;
float centerY = (topY + bottomY) / 2;
int vertexCount = vertexCache.Count;
for (int i = 0; i < vertexCount; i++)
UIVertex veretx = vertexCache[i];
if (veretx.position.y < centerY)
veretx.color = m_BottomColor;
else
veretx.color = m_TopColor;
vertexCache[i] = veretx;
//int vertexCount = vertexCache.Count;
//for (int i = 0; i < vertexCount; i++)
//
// UIVertex veretx = vertexCache[i];
// if (i % 6 == 0 || i % 6 == 1 || i % 6 == 5)
//
// veretx.color = m_TopColor;
//
// else
//
// veretx.color = m_BottomColor;
//
// vertexCache[i] = veretx;
//
以上是关于Unity中实现UI渐变的主要内容,如果未能解决你的问题,请参考以下文章