0

I'm trying to make a minipaint application which has three buttons(rectangle, circle and line). I'm having problem with selecting and moving shapes with mouse. For example I have this rectangle class which inherits color, thickness from shape:

class rectangle : shape
{
  public int length { get; set; }
  public int width { get; set; }

  public override void Draw(Graphics g)
  {
    g.DrawRectangle(new Pen(color), new Rectangle(startx, starty, width,length));
   }
 }

Now, I want my panel1_MouseDown to select a rectangle in my panel whenever I click on any part of rectangle. All drawn shapes are added to a list named lstShapsOnForm and drawable is an abstract class that has abstract method of draw and property x y.

abstract class Drawable
{
  public int x { get; set; }
  public int y { get; set; }
  public abstract void draw(Graphics g);
 }

 private void panel1_MouseDown(object sender, MouseEventArgs e)
 {
    foreach (Drawable o in lstShapsOnForm)
    {
       if (e.Location.X >= o.x || e.Location.X < o.x)
        propertyGrid1.SelectedObject = o;       
    }
 }

How should I make this work?

Aryan Firouzian
  • 1,940
  • 5
  • 27
  • 41
Zahra
  • 2,231
  • 3
  • 21
  • 41
  • Take a look at [How can I treat the circle as a control after drawing it? - Moving and selecting shapes](https://stackoverflow.com/q/38345828/3110834) or this post [How to drag and move shapes in C#](https://stackoverflow.com/q/38747027/3110834). – Reza Aghaei Oct 30 '17 at 14:43

1 Answers1

0

Simplest thing is to make it the responsibility of the shape to know if they have been clicked in, so add a IsInside method eg:

abstract class Drawable
{
  public int x { get; set; }
  public int y { get; set; }
  public abstract void draw(Graphics g);
  public abstract bool IsInside(int x, int y);
}

Then to test:

var shapeHit = lstShapsOnForm.FirstOrDefault(s => s.IsInside(e.Location.X, e.Location.Y));    
if (shapeHit != null)
  propertyGrid1.SelectedObject = shapeHit;   

For the rectangle, assuming you know the width and height (you should if you drew it), and assuming that the x and y properties are the top left corner, then it would be somehting like this:

public override bool IsInside(int mouseX, int mouseY) 
{
    return 
        mouseX >= x && 
        mouseX <= x + width &&
        mouseY >= y &&
        mouseY <= y + height;
}

For the circle and line ..... I suggest you google 'how to determine if x/y point is inside circle / on line'. It will involve testing using the radius (for the circle) and the 2 line points (for the line)

mikelegg
  • 1,197
  • 6
  • 10