项目中有涉及到,就贴出来交流
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
public class Typewriter_alpha : MonoBehaviour {
public float TimeSpan = 0.1f;
public int ColorSpan = 50;//1-50
public bool ColorAlphaSpan = true;
private bool changeFlag = true;
private string originStr;
private string nowStr;
private int index;
private float timePiece;
private string originColor;
private Dictionary<int,int> alphaLine = new Dictionary<int, int>();
private string ColorToHex(Color color){
int Val = 0;
Val |= Mathf.RoundToInt (color.r * 255f) << 24;
Val |= Mathf.RoundToInt (color.g * 255f) << 16;
Val |= Mathf.RoundToInt (color.b * 255f) << 8;
Val |= Mathf.RoundToInt (color.a * 255f);
return Val.ToString ("x8").Substring(0,6); //返回值去掉alpha值
}
//<color=#0000ff00></color> rgba a:0%00 25%40 50%80 100%ff
//使单字透明度渐变 需要加注
// Use this for initialization
void OnEnable () {
originStr = this.GetComponent<Text> ().text;
originColor = ColorToHex (this.GetComponent<Text> ().color);
this.GetComponent<Text> ().text = "";
nowStr = "";
index = 1;
changeFlag = true;
timePiece = Time.time;
alphaLine.Clear ();
if (ColorAlphaSpan)
alphaLine.Add (0, 0);
}
// Update is called once per frame
void Update () {
if (Time.time - timePiece > TimeSpan&&changeFlag) {
if (ColorAlphaSpan) {
if (alphaLine.Count != 0) {
for (int i = 0; i < index; ++i) {
if (i == index - 1 && !alphaLine.ContainsKey (i)) {
alphaLine.Add (i, 0);
}
if (alphaLine.ContainsKey (i)) {
if (alphaLine [i] >= 100) {
alphaLine.Remove (i);
nowStr += originStr.Substring (i, 1);
if (alphaLine.Count == 0)
nowStr = originStr;
} else {
nowStr += "<color=#" + originColor;
//int值小于10的时候补个0 不然就显示为白色而不是透明度很低的颜色了
if (alphaLine [i] < 10)
nowStr += "0"+alphaLine[i]+">";
else
nowStr += alphaLine [i].ToString () + ">";
nowStr += originStr.Substring (i, 1);
nowStr += "</color>";
alphaLine [i] += ColorSpan;
}
} else {
nowStr += originStr.Substring (i, 1);
}
}
this.GetComponent<Text> ().text = nowStr;
nowStr = "";
if (index < originStr.Length)
index++;
} else {
changeFlag = false;
}
} else {
this.GetComponent<Text> ().text = originStr.Substring (0, index++);
if (index > originStr.Length)
changeFlag = false;
}
timePiece = Time.time;
}
}
}