c# - 检查特定点 x,y 是否在矩形内

标签 c# geometry point rectangles

我正在尝试编写程序,通过矩形的宽度和高度以及它的上角点和左角点指定一个矩形。我希望程序允许用户输入点 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);
    }
}

最佳答案

我之前没有使用过 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 的文档时,请注意左侧有几个指向不同使用点的方法的链接。

关于c# - 检查特定点 x,y 是否在矩形内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22424155/

相关文章:

C#:用于创建随机均匀分布的潜在重叠范围的算法

iOS Swift - 动画绘制圆弧填充,而不是边框​​描边

javascript - three.js - 将具有长边的面拆分为两个面

python mpl : how to plot a point on a graph of 3D vectors, 和箭头头

r - 使用 scale_..._manual 将自定义图例添加到具有两个 geom_point 图层的 ggplot

c# - 拒绝访问!?我无法从 C 驱动器上的安装文件夹中打开文件

c# - 在将 XML 绑定(bind)到转发器之前对其进行过滤和排序?

java - 点是否在多边形内测试

c# - 在 Entity Framework 中使用TPT设计的多级继承

algorithm - 最小封闭球体的弹跳气泡算法