Search code examples
vb.netwinformsgradientlinear-gradientslineargradientbrush

Color Code Rows in a Data Grid Based on a Gradient in VB.Net Forms


I have a grid containing rows flagged with different priorities. I want to color the high priority rows red, low ones blue, etc.

I'd like to set the shade based on a mathmatically calculated gradient rather than arbitrarily assigning colors to specific priorities. How can I extract a single color from a single point along gradient?


Solution

  • How about something like

    VB.Net

    Private Shared Function ColorGradientRedToBlue(ByVal index As Single) As Color
        If index < 0 OrElse index > 1.0R Then
            Throw New ArgumentException("index must be between 0 and 1")
        End If
        Return Color.FromArgb(CInt(((1.0R - index) * 255)), 0, CInt((index * 255)))
    End Function
    

    C#

    static Color ColorGradientRedToBlue(float index)
    {
        if (index < 0 || index > 1.0)
            throw new ArgumentException("index must be between 0 and 1");
        return Color.FromArgb((int)((1.0 - index) * 255), 0 ,(int)(index * 255));
    }