Skip to content

Instantly share code, notes, and snippets.

@reveriejake
Last active November 18, 2022 09:20
Show Gist options
  • Save reveriejake/9b8d4de4a18b58f59e3294196b50c643 to your computer and use it in GitHub Desktop.
Save reveriejake/9b8d4de4a18b58f59e3294196b50c643 to your computer and use it in GitHub Desktop.
/* Written by Jacob Fletcher - 2022 | Free to alter and use! */
using UnityEngine;
namespace PicoGames
{
public static class GradientExtensions
{
/// <summary>
/// Converts the Gradient into a new texture.
/// </summary>
/// <param name="grad">Gradient to be converted</param>
/// <param name="width">Pixel width of texture to be created (default: 32x1)</param>
/// <param name="filterMode">Filter mode of the texture to be created</param>
public static Texture2D ToTexture2D(this Gradient grad, int width = 32, FilterMode filterMode = FilterMode.Bilinear)
{
Texture2D tex = new Texture2D(width, 1, TextureFormat.ARGB32, false);
tex.filterMode = filterMode;
tex.wrapMode = TextureWrapMode.Clamp;
for (int x = 0; x < tex.width; x++)
tex.SetPixel(x, 0, grad.Evaluate(x / (float)(tex.width - 2)));
tex.Apply();
return tex;
}
/// <summary>
/// Converts the Gradient into the provided texture.
/// </summary>
/// <param name="grad">Gradient to be converted</param>
/// <param name="texRef"></param>
/// <param name="width">Pixel width of texture to be created (default: 32x1)</param>
/// <param name="filterMode">Filter mode of the texture to be created (default: Bilinear)</param>
public static void ToTexture2D(this Gradient grad, ref Texture2D texRef, int width = 32, FilterMode filterMode = FilterMode.Bilinear)
{
if(texRef == null || texRef.width != width || texRef.height != 1 || texRef.filterMode != filterMode)
texRef = new Texture2D(width, 1, TextureFormat.ARGB32, false);
texRef.filterMode = filterMode;
texRef.wrapMode = TextureWrapMode.Clamp;
for (int x = 0; x < texRef.width; x++)
texRef.SetPixel(x, 0, grad.Evaluate(x / (float)(texRef.width - 2)));
texRef.Apply();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment