欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Unity3D实现渐变颜色效果

程序员文章站 2023-11-13 08:33:10
基于unity3d实现渐变颜色的简单脚本,代码很少,就不废话了,直接上代码和效果图。 效果图: using system; using system.co...

基于unity3d实现渐变颜色的简单脚本,代码很少,就不废话了,直接上代码和效果图。

Unity3D实现渐变颜色效果

效果图:

using system;
using system.collections.generic;
using unityengine;
using unityengine.ui;
 
namespace extrafoundation.components
{
 [addcomponentmenu("ui/effects/gradient")]
 public class uigradient : basemesheffect
 {
  #region public declarations
  public enum type
  {
   vertical,
   horizontal
  }
  #endregion
 
  #region public properties
  public type gradienttype = type.vertical;
  [range(-1f, 1f)]
  public float offset = 0f;
  public gradient gradient;
  #endregion
 
  #region public methods
  public override void modifymesh(vertexhelper helper)
  {
   if (!isactive() || helper.currentvertcount == 0)
   {
    return;
   }
 
   vertexlist.clear();
   helper.getuivertexstream(vertexlist);
 
   int ncount = vertexlist.count;
   switch (gradienttype)
   {
    case type.vertical:
     {
      float fbottomy = vertexlist[0].position.y;
      float ftopy = vertexlist[0].position.y;
      float fypos = 0f;
 
      for (int i = ncount - 1; i >= 1; --i)
      {
       fypos = vertexlist[i].position.y;
       if (fypos > ftopy)
        ftopy = fypos;
       else if (fypos < fbottomy)
        fbottomy = fypos;
      }
 
      float fuielementheight = 1f / (ftopy - fbottomy);
      uivertex v = new uivertex();
 
      for (int i = 0; i < helper.currentvertcount; i++)
      {
       helper.populateuivertex(ref v, i);
       v.color = gradient.evaluate((v.position.y - fbottomy) *
        fuielementheight - offset);
       helper.setuivertex(v, i);
      }
     }
     break;
    case type.horizontal:
     {
      float fleftx = vertexlist[0].position.x;
      float frightx = vertexlist[0].position.x;
      float fxpos = 0f;
 
      for (int i = ncount - 1; i >= 1; --i)
      {
       fxpos = vertexlist[i].position.x;
       if (fxpos > frightx)
        frightx = fxpos;
       else if (fxpos < fleftx)
        fleftx = fxpos;
      }
 
      float fuielementwidth = 1f / (frightx - fleftx);
      uivertex v = new uivertex();
 
      for (int i = 0; i < helper.currentvertcount; i++)
      {
       helper.populateuivertex(ref v, i);
       v.color = gradient.evaluate((v.position.x - fleftx) *
        fuielementwidth - offset);
       helper.setuivertex(v, i);
      }
 
     }
     break;
    default:
     break;
   }
  }
  #endregion
  
  #region internal fields
  private list<uivertex> vertexlist = new list<uivertex>();
  #endregion
 }
}

虽然支持的内容不多,但是小而精,希望对大家有用。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。