125 lines
3.7 KiB
C#

using Assets.Scripts;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class PFUISlider : MonoBehaviour
{
private Text text;
private Slider slider;
public System.Func<float, float> valueHandler = (a) => a * 100;
private List<Color> colorGradientList;
private void Awake()
{
text = transform.Find("Text").GetComponent<Text>();
slider = transform.GetComponent<Slider>();
//text.text = $"{(slider.value * 100).ToString("#0")}";
//slider.onValueChanged.AddListener((f) =>
//{
// text.text = $"{valueHandler(f).ToString("#0")}";
//});
colorGradientList = SetColorGradient(new List<Color>
{
Utils.HexToColorHtml("#ffffff"),
Utils.HexToColorHtml("#27DFE3"),
Utils.HexToColorHtml("#27E363"),
Utils.HexToColorHtml("#E3D427"),
Utils.HexToColorHtml("#E33B27"),
},
new List<int>
{
50,50,100,100
});
}
public bool runCallback = false;
public void SetValueChanged(System.Action<float> a)
{
this.ValueChangedHandler = a;
slider = transform.GetComponent<Slider>();
slider.onValueChanged.RemoveAllListeners();
UIManager.AddEvent(slider.gameObject, EventTriggerType.EndDrag, (e) =>
{
OnValueChanged();
});
slider.onValueChanged.AddListener((f) =>
{
current = f;
});
}
float current;
System.Action<float> ValueChangedHandler;
private void OnValueChanged()
{
float f = current;
var step = 1f / (colorGradientList.Count - 1);
var index = (int)Math.Round(f / step, 0);
slider.targetGraphic.color = colorGradientList[index];
text.text = $"{valueHandler(f):#0}";
this.ValueChangedHandler?.Invoke(f);
}
public void SetValue(float a,bool silent = false)
{
a = a > 1 ? 1 : a;
a = a < 0 ? 0 : a;
slider.value = a;
text.text = $"{valueHandler(a):#0}";
if(!silent)
OnValueChanged();
}
public float GetValue()
{
return slider.value;
}
public List<Color> SetColorGradient(List<Color> list, int divideCount)
{
var res = new List<Color>();
for (int i = 0; i < list.Count - 1; i++)
{
Color c = list[i], nc = list[i + 1];
var diff = new Tuple<float, float, float>((nc.r - c.r) / divideCount, (nc.g - c.g) / divideCount, (nc.b - c.b) / divideCount);
for (int j = 0; j < divideCount; j++)
{
res.Add(new Color(c.r + diff.Item1 * j, c.g + diff.Item2 * j, c.b + diff.Item3 * j));
}
}
return res;
}
public List<Color> SetColorGradient(List<Color> list, List<int> divideList)
{
if (list.Count != divideList.Count+1) return null;
var res = new List<Color>();
for (int i = 0; i < list.Count - 1; i++)
{
Color c = list[i], nc = list[i + 1];
var divideCount = divideList[i];
var diff = new Tuple<float, float, float>((nc.r - c.r) / divideCount, (nc.g - c.g) / divideCount, (nc.b - c.b) / divideCount);
for (int j = 0; j < divideCount; j++)
{
res.Add(new Color(c.r + diff.Item1 * j, c.g + diff.Item2 * j, c.b + diff.Item3 * j));
}
}
return res;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}