Calculate Minimum Bounding Rectangle Of 2D Shape By Coordinates

后端 未结 3 1220
醉酒成梦
醉酒成梦 2021-02-08 10:08

I have a solution that uses spatial data to represent a cluster of points on a map. I have the need to used the coordinates that represent the extents of a cluster to find the m

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-08 10:41

    One possible, though simple, way to do it could be like this:

    public Rectangle Test(List points)
    {
        // Add checks here, if necessary, to make sure that points is not null,
        // and that it contains at least one (or perhaps two?) elements
    
        var minX = points.Min(p => p.X);
        var minY = points.Min(p => p.Y);
        var maxX = points.Max(p => p.X);
        var maxY = points.Max(p => p.Y);
    
        return new Rectangle(new Point(minX, minY), new Size(maxX-minX, maxY-minY));
    }
    

    This does of course assume that you're looking for a rectangle that is aligned vertically and horizontally. So if you're looking for the smallest possible rectangle, no matter how it is rotated, this is not for you.

提交回复
热议问题