检查一个特定的点(x,y)是否在矩形内

本文关键字:是否 一个 检查 | 更新日期: 2023-09-27 17:50:20

我正在尝试编写程序,该程序通过其宽度和高度及其顶部和左角点指定矩形。我希望程序允许用户输入点x,y,然后我的目标是让程序确定该点是否在矩形内。

这是我的代码到目前为止,但我不确定如何进行。谁能帮我实现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);
    }
}

检查一个特定的点(x,y)是否在矩形内

我以前没有使用过System.Drawing.Rectangle类,但在我看来,您可以使用Contains(Point)方法。这里是该文档的链接:http://msdn.microsoft.com/en-us/library/22t27w02(v=vs.110).aspx

可以看到,传递给Contains()的参数类型是Point。使用用户输入的x、y值创建该类型的变量,并将其传递给Contains()方法。以下是Point结构的链接:http://msdn.microsoft.com/en-us/library/system.drawing.point(v=vs.110).aspx

当您查看Point的文档时,请注意左边有几个指向不同使用点的方法的链接。

在不知道它是否是直角三角形或三角形方向的情况下,很难给出精确的答案,但我使用的一般方法是获得顶点之间的夹角以及点与每个顶点之间的夹角。然后,您可以使用角度来进行边界检查。

相关文章: