Search code examples
arraysswiftmaxminimum

Creating a CGRect that encompasses a UIBezierPath and NSArray x Array in the process


All I need to do is to create a CGRect that encompasses a UIBezierPath and I have an array of CGPoint.

To create this CGRect all I need to do is to enumerate the array of CGPoint and find the minimum and maximum X and Y coordinates.

Then I remembered that the old and good NSArray had this function called valueForKeyPath that could be used in conjunction with something like valueForKeyPath:@max.x or valueForKeyPath:@min.x that would do the magic to find the minimum and maximum values of x and y.

I am new to Swift. This is the first time I am using Swift to create serious code.

Is there any magic in Swift arrays that can be used to do that, instead of creating complex enumerations and loops?


Solution

  • The easy solution, if you already have the UIBezierPath, is to just get its bounds:

    let rect = path.bounds
    

    If you have an array of points and want the bounds of that encompasses those points, you could min and max the x and y coordinates, but I might reduce the union of all the points:

    let points = [
        CGPoint(x: 200, y: 200),
        CGPoint(x: 300, y: 300),
        CGPoint(x: 200, y: 400),
        CGPoint(x: 100, y: 300)
    ]
    
    let rect = points.first.map { firstPoint in
        points.dropFirst()
            .reduce(CGRect(origin: firstPoint, size: .zero)) { rect, point in
                rect.union(CGRect(origin: point, size: .zero))
        }
    }