今日在做項目中發現,很多時候需要對文字多特殊處理,漸變就是最常用的。
特別是文字特別多,還有動態的時候,就不能只靠圖了,否則包的大小就吃不消了。
在網上搜到雨松寫的漸變代碼,於是就拿來用了。可是版本不一樣,我的是5.5.0版本,函數ModifyMesh的參數已經是VertexHelper了,所以就需要改動改動
具體代碼如下:
---------------------
作者:蘇小敗在路上
來源:CSDN
原文:https://blog.csdn.net/pz789as/article/details/65628796
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; [AddComponentMenu("UI/Effects/TextGradient")] [RequireComponent(typeof(Text))] public class UICustomTextGradient : BaseMeshEffect { public Color32 topColor = Color.white; public Color32 bottomColor = Color.black; //后面自己添加的控制中心移動屬性,有時候看着漸變不順眼,中心偏離高或者低了,就可以通過這個去調整 [RangeAttribute(0, 1)] public float center = 0.5f; 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; 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 height = topY - bottomY; for (var i = 0; i < count; i++) { var vertex = vertexs[i]; //使用處理過后的顏色 // var color = Color32.Lerp(bottomColor, topColor, (vertex.position.y - bottomY) / height); var color = CenterColor(bottomColor, topColor, (vertex.position.y - bottomY) / height); vertex.color = color; vh.SetUIVertex(vertex, i); } } //加了一個對顏色處理的函數,主要調整中心的位置 private Color32 CenterColor(Color32 bc, Color32 tc, float time){ if (center == 0){ return bc; }else if (center == 1){ return tc; }else{ var centerColor = Color32.Lerp(bottomColor, topColor, 0.5f); var resultColor = tc; if (time < center) { resultColor = Color32.Lerp(bottomColor, centerColor, time / center); }else{ resultColor = Color32.Lerp(centerColor, topColor, (time - center)/(1-center)); } return resultColor; } } } --------------------- 作者:蘇小敗在路上 來源:CSDN 原文:https://blog.csdn.net/pz789as/article/details/65628796 版權聲明:本文為博主原創文章,轉載請附上博文鏈接!