Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I need to draw lines in my C#/WPF application, where the lines follow the mouse cursor movement.

I am able to trace the mouse cursor and show a blue-colored path.

How can I use gradient to create the line? Since I don't know the length of the line, I can't preset the individual colors of the gradient. Is there a way I can say "Change the line color from blue-yellow-red-blue gradually,and then repeat"?

Thanks!
Posted

 
Share this answer
 
Comments
Member 3293815 12-Jun-14 6:01am    
Hi Richard, thanks for the link!

I have gone through MSDN links, but none of them satisfied my requirements. To clarify my question further, I am implementing a timer. Every time timer goes out, I need to apply new color to the line.

Now, the color should be changed every second, so that the change in color is not abrupt. I am not able to choose color set, so that the change in color is gradual. Any suggestions, please?
Something like this then?

System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
Line gradientLine;
LinearGradientBrush gradBrush = new LinearGradientBrush();

        void Window_Loaded(object sender, RoutedEventArgs e)
        {
            gradBrush.GradientStops.Add(new GradientStop(Colors.Red, 0));
            gradBrush.GradientStops.Add(new GradientStop(Colors.Orange, 0.5));
            gradBrush.GradientStops.Add(new GradientStop(Colors.Yellow, 1));
            gradBrush.GradientStops.Add(new GradientStop(Colors.Green, 1.5));
            gradBrush.GradientStops.Add(new GradientStop(Colors.Blue, 2));
            gradBrush.GradientStops.Add(new GradientStop(Colors.Indigo, 2.5));
            gradBrush.GradientStops.Add(new GradientStop(Colors.Violet, 3));
            gradBrush.GradientStops.Add(new GradientStop(Colors.Purple, 3.5));
            gradientLine =  new Line() { X1 = 0, Y1 = 0, X2 = 100, Y2 = 100, StrokeThickness = 1, Stroke = gradBrush  };
            cnvCanvas.Children.Add(gradientLine);

            timer.Tick += timer_Tick;
            timer.Interval = new TimeSpan(0, 0, 0, 0, 1000/30);
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            for (int i = 0; i < gradBrush.GradientStops.Count; ++i)
            {
                gradBrush.GradientStops[i].Offset = gradBrush.GradientStops[i].Offset - 0.01;
                if (gradBrush.GradientStops[i].Offset < -1) gradBrush.GradientStops[i].Offset += 4;
            }

        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900