Tanoda
unity-ui-extensions/Runtime/Scripts/Controls/ColorPicker/SVBoxSlider.cs
Go to the documentation of this file.
1
3
4
6{
7 [RequireComponent(typeof(BoxSlider), typeof(RawImage)), ExecuteInEditMode()]
8 public class SVBoxSlider : MonoBehaviour
9 {
11
12 private BoxSlider slider;
13 private RawImage image;
14
15 private float lastH = -1;
16 private bool listen = true;
17
19 {
20 get
21 {
22 return transform as RectTransform;
23 }
24 }
25
26 private void Awake()
27 {
28 slider = GetComponent<BoxSlider>();
29 image = GetComponent<RawImage>();
30
31 RegenerateSVTexture();
32 }
33
34 private void OnEnable()
35 {
36 if (Application.isPlaying && picker != null)
37 {
38 slider.OnValueChanged.AddListener(SliderChanged);
39 picker.onHSVChanged.AddListener(HSVChanged);
40 }
41 }
42
43 private void OnDisable()
44 {
45 if (picker != null)
46 {
47 slider.OnValueChanged.RemoveListener(SliderChanged);
48 picker.onHSVChanged.RemoveListener(HSVChanged);
49 }
50 }
51
52 private void OnDestroy()
53 {
54 if (image.texture != null)
55 DestroyImmediate(image.texture);
56 }
57
58#if UNITY_EDITOR
59 private void OnValidate()
60 {
61 image = GetComponent<RawImage>();
62 RegenerateSVTexture();
63 }
64#endif
65
66 private void SliderChanged(float saturation, float value)
67 {
68 if (listen)
69 {
70 picker.AssignColor(ColorValues.Saturation, saturation);
71 picker.AssignColor(ColorValues.Value, value);
72 }
73 listen = true;
74 }
75
76 private void HSVChanged(float h, float s, float v)
77 {
78 if (lastH != h)
79 {
80 lastH = h;
81 RegenerateSVTexture();
82 }
83
84 if (s != slider.NormalizedValueX)
85 {
86 listen = false;
87 slider.NormalizedValueX = s;
88 }
89
90 if (v != slider.NormalizedValueY)
91 {
92 listen = false;
93 slider.NormalizedValueY = v;
94 }
95 }
96
97 private void RegenerateSVTexture()
98 {
99 double h = picker != null ? picker.H * 360 : 0;
100
101 if (image.texture != null)
102 DestroyImmediate(image.texture);
103
104 Texture2D texture = new Texture2D(100, 100)
105 {
106 hideFlags = HideFlags.DontSave
107 };
108 for (int s = 0; s < 100; s++)
109 {
110 Color32[] colors = new Color32[100];
111 for (int v = 0; v < 100; v++)
112 {
113 colors[v] = HSVUtil.ConvertHsvToRgb(h, (float)s / 100, (float)v / 100, 1);
114 }
115 texture.SetPixels32(s, 0, 1, 100, colors);
116 }
117 texture.Apply();
118
119 image.texture = texture;
120 }
121 }
122}
UnityEngine.UI.Extensions.BoxSlider BoxSlider