Draw a curve with sharply delineated colors in C#

[colors]

The post Draw a curve with multiple colors in C# shows how you can draw a curve that shades gradually from one color to another as the curve’s Y coordinates change. However, you might not always want the colors to change gradually. This example makes the colors change sharply.

See the previous example for the basic approach. The only difference is that this example gives its LinearGradientBrush a different set of colors.

The previous example’s brush defined colors at various points along the gradient. The brush automatically interpolates to make the colors blend together.

[colors]
This example defines two color positions in the gradient for each color. Then the brush must keep the color the same between two instances of the same color. For example, the brush is red at position 0.0 and 0.2 so it must also be red in between. This effectively anchors the colors in the brush.

Figure 1 shows the color gradients used by the previous example (top) and this example (bottom).

The following code shows how this example defines its brush.

// Make a brush for the curve.
using (LinearGradientBrush brush =
    new LinearGradientBrush(world_rect,
        Color.Red, Color.Blue, 270))
{
    ColorBlend blend = new ColorBlend();
    blend.Colors = new Color[]
    {
        Color.Red, Color.Red,
        Color.Orange, Color.Orange,
        Color.Yellow, Color.Yellow,
        Color.Green, Color.Green,
        Color.Blue, Color.Blue,
    };
    blend.Positions =
        new float[]
        {
            0.0f, 0.2f,
            0.2f, 0.4f,
            0.4f, 0.6f, 
            0.6f, 0.8f,
            0.8f, 1.0f,
        };
    brush.InterpolationColors = blend;
    ...
}

The code creates the brush as before. It then creates a ColorBlend and assigns its colors and the colors' positions. Notice that each color appears twice and that adjacent colors have the same positions.

There's still a small amount of blending between colors, but it's not very noticeable. You could eliminate it entirely by using a TextureBrush defined by an image that positions the colors exactly.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in drawing, graphics and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *