Reputation: 345
I'm trying to write program which specifies a rectangle via its width and height and its top and left corner point. I want the program to allow a user to input a point x,y after which my goal is to have the program determine whether the point is inside the rectangle.
Here is my code so far, but I'm not sure how to proceed. Can anyone help me with the implementation of bool Rectangle.Contains(x, y)
?
public struct Rectangle
{
// declare the fields
public int Width;
public int Height;
public int Top;
public int Left;
// define a constructor
public Rectangle(int Width, int Height, int Top, int Left)
{
this.Width = Width;
this.Height = Height;
this.Top = Top;
this.Left = Left;
}
public bool Contains(int x, int y) { }
}
class MainClass
{
public static void Main()
{
Console.WriteLine("Creating a Rectangle instance");
Rectangle myRectangle = new Rectangle(6, 2, 1, -1);
Console.WriteLine("myRectangle.Width = " + myRectangle.Width);
Console.WriteLine("myRectangle.Height = " + myRectangle.Height);
Console.WriteLine("myRectangle.Top = " + myRectangle.Top);
Console.WriteLine("myRectangle.Left = " + myRectangle.Left);
}
}
Upvotes: 6
Views: 19238
Reputation: 237
I haven't used the System.Drawing.Rectangle
class before, but it looks to me that you could use the Contains(Point)
method. Here is a link to that documentation: http://msdn.microsoft.com/en-us/library/22t27w02(v=vs.110).aspx
As you can see, the parameter passed to Contains()
is of type Point
. Create a variable of that type using the user-entered x,y values and pass it to the Contains()
method. Here is a link to the Point
structure: http://msdn.microsoft.com/en-us/library/system.drawing.point(v=vs.110).aspx
When you view the documentation for Point
, notice that off to the left there are several links to different ways to use points.
Upvotes: 4
Reputation: 3122
Without knowing whether it's a right triangle or the orientation of the triangle, it's hard to give a precise answer, but the general approach I would use would be to get the angles between the vertices and the angles of the point versus each vertex. You can then use the angles to do a boundary check.
Upvotes: -1