I have a c# WinForm project with the following code to draw Rectangles and Ellipses:
public partial class Form1 : Form
{
List<Rectangle> _rectangles = new();
List<Rectangle> _ellipses = new();
Rectangle _rectInProgress;
bool DrawingRectangle = false;
bool DrawingEllipse = false;
public Form1()
{
InitializeComponent();
DoubleBuffered = true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (DrawingRectangle || DrawingEllipse)
{
_rectInProgress = new Rectangle(e.Location, new Size());
}
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (MouseButtons == MouseButtons.Left && (DrawingRectangle || DrawingEllipse))
{
_rectInProgress.Width = e.Location.X - _rectInProgress.X;
_rectInProgress.Height = e.Location.Y - _rectInProgress.Y;
Invalidate();
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
if (DrawingRectangle)
{
_rectangles.Add(_rectInProgress);
Invalidate();
}
else if (DrawingEllipse)
{
_ellipses.Add(_rectInProgress);
Invalidate();
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (_rectangles.Any())
{
e.Graphics.DrawRectangles(new Pen(Color.Blue, 3), _rectangles.ToArray());
}
if (_ellipses.Any())
{
foreach (var ell in _ellipses)
{
e.Graphics.DrawEllipse(new Pen(Color.Blue, 3), ell);
}
}
if (MouseButtons == MouseButtons.Left)
{
if (DrawingEllipse)
{
e.Graphics.DrawEllipse(new Pen(Color.Red, 3), _rectInProgress);
}
else if (DrawingRectangle)
{
e.Graphics.DrawRectangle(new Pen(Color.Red, 3), _rectInProgress);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
DrawingRectangle = !DrawingRectangle;
DrawingEllipse = false;
}
private void button2_Click(object sender, EventArgs e)
{
DrawingEllipse = !DrawingEllipse;
DrawingRectangle = false;
}
}
The next step is to make the shapes selectable, so they can be resized. I am new to this kind of thing, so I have no idea where to start. I found many examples on the internet, but they all have one thing in common: they check if the cursor clicked WITHIN the shape. I need to check if the cursor clicked ON the shape (the borders).
Anyone any tips on how to proceed? Thanks in advance!
If this variant is interesting, I can think about ellipses.