Click here to Skip to main content
15,891,708 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I've been thinking for a long time about how to create a project in C# in winforms, where I select 2 points with the mouse and create a line between them that will have the whole RGB spectrum.


What I have tried:

I try this, but it isnt what I want:
public partial class Form1 : Form
    {
        class Line
        {
            public Point Start { get; set; }
            public Point End { get; set; }
        }

        public Form1()
        {
            var pb = new PictureBox { Parent = this, Dock = DockStyle.Fill };
            Line line = null;

            pb.MouseMove += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    line.End = e.Location;
                    pb.Invalidate();
                }
            };
            pb.MouseDown += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                    line = new Line { Start = e.Location, End = e.Location };
            };
            var lines = new List<Line>();
            pb.MouseUp += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                    lines.Add(line);
            };
            pb.Paint += (s, e) =>
            {
                if (line != null)
                    e.Graphics.DrawLine(Pens.Red, line.Start, line.End);

                foreach (var l in lines)
                    e.Graphics.DrawLine(Pens.Silver, l.Start, l.End);
            };
        }
    }
Posted
Updated 11-Jun-22 3:40am

line is a local variable - it exists only for the duration of the constructor method - and so a copy of the current value - null - will be passed to the Paint method every time it is called to handle the Paint event. Similarly, the changes you make to line in your mouse handlers will not be reflected in the Paint event version.

Make it a class level private field, and it may start to work ... but I suspect that you need to give your PictureBox a size, and a location, and attach it to the Form.Controls collection.
 
Share this answer
 
v2
Use a Linear Gradient.

How to: Create a Linear Gradient - Windows Forms .NET Framework | Microsoft Docs[^]

(It's even simpler in WPF / UWP / XAML).
 
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