Skip to content

Instantly share code, notes, and snippets.

@mattatz
Created November 28, 2016 04:14
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mattatz/a8c697e212b653ca9ce966797bb93a3c to your computer and use it in GitHub Desktop.
Save mattatz/a8c697e212b653ca9ce966797bb93a3c to your computer and use it in GitHub Desktop.
Gradient Texture2D Generator for Unity.
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.IO;
using System.Collections;
namespace mattatz.Utils {
public class GradientTexGen {
public static Texture2D Create (Gradient grad, int width = 32, int height = 1) {
var gradTex = new Texture2D(width, height, TextureFormat.ARGB32, false);
gradTex.filterMode = FilterMode.Bilinear;
float inv = 1f / (width - 1);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
var t = x * inv;
Color col = grad.Evaluate(t);
gradTex.SetPixel(x, y, col);
}
}
gradTex.Apply();
return gradTex;
}
}
#if UNITY_EDITOR
public class GradientTexCreator : EditorWindow {
[SerializeField] Gradient gradient;
[SerializeField] int width = 128;
[SerializeField] int height = 16;
[SerializeField] string fileName = "Gradient";
[MenuItem("Custom/GradientTex")]
static void Init() {
EditorWindow.GetWindow(typeof(GradientTexCreator));
}
void OnGUI () {
EditorGUI.BeginChangeCheck();
SerializedObject so = new SerializedObject(this);
EditorGUILayout.PropertyField(so.FindProperty("gradient"), true, null);
if (EditorGUI.EndChangeCheck()) {
so.ApplyModifiedProperties();
}
using (new GUILayout.HorizontalScope()) {
GUILayout.Label("width", GUILayout.Width(80f));
int.TryParse(GUILayout.TextField(width.ToString(), GUILayout.Width(120f)), out width);
}
using (new GUILayout.HorizontalScope()) {
GUILayout.Label("height", GUILayout.Width(80f));
int.TryParse(GUILayout.TextField(height.ToString(), GUILayout.Width(120f)), out height);
}
using (new GUILayout.HorizontalScope()) {
GUILayout.Label("name", GUILayout.Width(80f));
fileName = GUILayout.TextField(fileName, GUILayout.Width(120f));
GUILayout.Label(".png");
}
if(GUILayout.Button("Save")) {
string path = EditorUtility.SaveFolderPanel("Select an output path", "", "");
if(path.Length > 0) {
var tex = GradientTexGen.Create(gradient, width, height);
byte[] pngData = tex.EncodeToPNG();
File.WriteAllBytes(path + "/" + fileName + ".png", pngData);
AssetDatabase.Refresh();
}
}
}
}
#endif
}
@all12jus
Copy link

all12jus commented Mar 9, 2021

I found a bug with this code.
Line 17 should actually be: float inv = 1f / width;
It was showing one pixel of the gradient on the other side of the image. Other than that, Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment