Draw a curve with more sharply delineated colors in C#

[colors]

In the post Draw a curve with sharply delineated colors in C# I mentioned that you could achieve even more sharply defined colors if you use a TextureBrush. Naturally I couldn’t let it reset so here’s an example that does just that. The following code shows how the program creates its brush and draws the curve.

// Make an image for the brush.
using (Bitmap bm = new Bitmap(100, 100))
{
    using (Graphics gr = Graphics.FromImage(bm))
    {
        gr.Clear(Color.White);
        gr.FillRectangle(Brushes.Red, 0, 80, 100, 20);
        gr.FillRectangle(Brushes.Orange, 0, 60, 100, 20);
        gr.FillRectangle(Brushes.Yellow, 0, 40, 100, 20);
        gr.FillRectangle(Brushes.Green, 0, 20, 100, 20);
        gr.FillRectangle(Brushes.Blue, 0, 0, 100, 20);
    }

    // Make a brush from the image.
    using (TextureBrush brush = new TextureBrush(bm))
    {
        // Make a thick pen defined by the brush.
        using (Pen pen = new Pen(brush, 3))
        {
            pen.LineJoin = LineJoin.Bevel;

            // Draw the curve.
            Random rand = new Random();
            if (chkCurved.Checked)
                e.Graphics.DrawCurve(pen, Points);
            else
                e.Graphics.DrawLines(pen, Points);
        }
    }
}

The code makes a Bitmap big enough to fill the drawing coordinates. It creates a Graphics object and uses it to color the Bitmap with horizontal stripes of color.

The code then creates a TextureBrush that uses the Bitmap. It then draws the curve as in the earlier examples.

There’s still a tiny amount of color blending. That’s caused when the program transforms the brush from drawing coordinates into screen coordinates. If you really want control of every pixel’s color, you’ll probably need to perform the coordinate conversions yourself and then draw in device coordinates so there’s no automatic scaling.


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.

One Response to Draw a curve with more sharply delineated colors in C#

  1. Maxy says:

    This is very nicely.

Leave a Reply

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