/*
* @author Valentin Simonov / http://va.lent.in/
*/
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace TouchScript.Behaviors.Cursors.UI
{
///
/// Generates a texture with a circle gradient.
///
[HelpURL("http://touchscript.github.io/docs/html/T_TouchScript_Behaviors_Cursors_UI_GradientTexture.htm")]
public class GradientTexture : MonoBehaviour
{
///
/// Resolution in pixels.
///
public enum Res
{
///
/// 16x16
///
Pix16 = 16,
///
/// 32x32
///
Pix32 = 32,
///
/// 64x64
///
Pix64 = 64,
///
/// 128x128
///
Pix128 = 128,
///
/// 256x256
///
Pix256 = 256,
///
/// 512x512
///
Pix512 = 512
}
///
/// The gradient.
///
public Gradient Gradient = new Gradient();
///
/// Gradient's name. Used to cache textures.
///
public string Name = "Gradient";
///
/// Texture resolution.
///
public Res Resolution = Res.Pix128;
private Texture2D texture;
private static Dictionary textureCache = new Dictionary();
///
/// Generates the gradient texture.
///
/// Generated texture.
public Texture2D Generate()
{
var res = (int) Resolution;
var tex = new Texture2D(res, 1, TextureFormat.ARGB32, false, true)
{
name = Name,
filterMode = FilterMode.Bilinear,
wrapMode = TextureWrapMode.Clamp
};
var colors = new Color[res];
float div = res;
for (var i = 0; i < res; i++)
{
float t = i / div;
colors[i] = Gradient.Evaluate(t);
}
tex.SetPixels(colors);
tex.Apply(false, true);
return tex;
}
private void Start()
{
var hash = Name.GetHashCode();
if (!textureCache.TryGetValue(hash, out texture))
{
texture = Generate();
textureCache.Add(hash, texture);
}
apply();
}
private void OnValidate()
{
refresh();
}
private void refresh()
{
if (texture != null)
DestroyImmediate(texture);
texture = Generate();
apply();
}
private void apply()
{
var r = GetComponent();
if (r == null) throw new Exception("GradientTexture must be on an UI element with RawImage component.");
r.texture = texture;
}
}
}