|
| 1 | +// returns gradient Texture2D (size=256x1) |
| 2 | + |
| 3 | +using UnityEngine; |
| 4 | + |
| 5 | +namespace UnityLibrary |
| 6 | +{ |
| 7 | + public static class GradientTextureMaker |
| 8 | + { |
| 9 | + const int width = 256; |
| 10 | + const int height = 1; |
| 11 | + |
| 12 | + public static Texture2D Create(Color[] colors, TextureWrapMode textureWrapMode = TextureWrapMode.Clamp, FilterMode filterMode = FilterMode.Point, bool isLinear = false, bool hasMipMap = false) |
| 13 | + { |
| 14 | + if (colors == null || colors.Length == 0) |
| 15 | + { |
| 16 | + Debug.LogError("No colors assigned"); |
| 17 | + return null; |
| 18 | + } |
| 19 | + |
| 20 | + int length = colors.Length; |
| 21 | + if (colors.Length > 8) |
| 22 | + { |
| 23 | + Debug.LogWarning("Too many colors! maximum is 8, assigned: " + colors.Length); |
| 24 | + length = 8; |
| 25 | + } |
| 26 | + |
| 27 | + // build gradient from colors |
| 28 | + var colorKeys = new GradientColorKey[length]; |
| 29 | + var alphaKeys = new GradientAlphaKey[length]; |
| 30 | + |
| 31 | + float steps = length - 1f; |
| 32 | + for (int i = 0; i < length; i++) |
| 33 | + { |
| 34 | + float step = i / steps; |
| 35 | + colorKeys[i].color = colors[i]; |
| 36 | + colorKeys[i].time = step; |
| 37 | + alphaKeys[i].alpha = colors[i].a; |
| 38 | + alphaKeys[i].time = step; |
| 39 | + } |
| 40 | + |
| 41 | + // create gradient |
| 42 | + Gradient gradient = new Gradient(); |
| 43 | + gradient.SetKeys(colorKeys, alphaKeys); |
| 44 | + |
| 45 | + // create texture |
| 46 | + Texture2D outputTex = new Texture2D(width, height, TextureFormat.ARGB32, false, isLinear); |
| 47 | + outputTex.wrapMode = textureWrapMode; |
| 48 | + outputTex.filterMode = filterMode; |
| 49 | + |
| 50 | + // draw texture |
| 51 | + for (int i = 0; i < width; i++) |
| 52 | + { |
| 53 | + outputTex.SetPixel(i, 0, gradient.Evaluate((float)i / (float)width)); |
| 54 | + } |
| 55 | + outputTex.Apply(false); |
| 56 | + |
| 57 | + return outputTex; |
| 58 | + } // BuildGradientTexture |
| 59 | + |
| 60 | + } // class |
| 61 | +} // namespcae |
0 commit comments