Skip to content

Instantly share code, notes, and snippets.

@tmacharia
Last active February 1, 2020 00:15
Show Gist options
  • Save tmacharia/dba54572df1b598b8b2bbc08c886ed22 to your computer and use it in GitHub Desktop.
Save tmacharia/dba54572df1b598b8b2bbc08c886ed22 to your computer and use it in GitHub Desktop.
Generate a smooth looking linear color gradient for use in UWP apps that for example scales from transparent to Black
private void Usage()
{
MyGrid.Background = new LinearGradientBrush()
{
GradientStops = GetGradientStops(Colors.Black, 8)
};
}
/// <summary>
/// Generate a smooth <see cref="GradientStopCollection"/> from transparent to the specified target
/// <see cref="Color"/> with the specified <paramref name="numOfStops"/>.
/// </summary>
/// <param name="color">Target color at the end of gradient</param>
/// <param name="numOfStops">Number of gradient stops to add to collection. For better & smoother gradients, high
/// number of stops are recommended e.g 5+ but try not use many stops i.e 20 max, since that will do the trick.
/// </param>
/// <returns>A <see cref="GradientStopCollection"/></returns>
private GradientStopCollection GetGradientStops(Color color,int numOfStops = 10)
{
GradientStopCollection collection = new GradientStopCollection();
int opacity = 0; // sets color initially to transparent.;
double offset = 0; // indicates the start point.
for (int i = 0; i < numOfStops + 1; i++)
{
collection.Add(GetGradientStop(color, opacity, offset));
if (opacity < 85)
{
offset += 0.1;
opacity += 17;
}
else
{
offset += 0.1;
opacity += 3;
}
}
return collection;
}
/// <summary>
/// Create a <see cref="GradientStop"/> to be used at a specific location in your
/// <see cref="GradientStopCollection"/> using the specified color.
/// </summary>
/// <param name="color"><see cref="Color"/> to apply at the specified spot.</param>
/// <param name="opacity">Opacity of the color. Range from 0 to 100. This modifies the alpha channel of
/// the color to set it to your desired opacity.</param>
/// <param name="offset">Location of the color. Ranges from 0 to 1.</param>
/// <returns>A <see cref="GradientStop"/></returns>
private GradientStop GetGradientStop(Color color, int opacity=0, double offset = 0)
{
return new GradientStop() { Color = color.ToggleOpacity(opacity), Offset = offset };
}
public static class ColorExts
{
public static Color ToggleOpacity(this Color col, int? opacity = 100)
{
int alpha = 255;
if (opacity.HasValue)
{
alpha = opacity.Value * 255 / 100;
}
return Color.FromArgb((byte)alpha, col.R, col.G, col.B);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment