I'm wanting to get the lowest and highest x and y coordinates from the touchesmoved event no matter what the shape being drawn is. Basically I want to create a cgrect that encompasses the shape. I have no idea how to go about this.
There are various ways to do this.
UIBezierPath
has a bounds method that will give you a bounding rectangle that contains all the points in the path. If you are building your shape into a UIBezierPath
that should be all you need.
If you need to track the bounds yourself, set up some variables and adjust them as needed:
var minY = CGFloat.greatestFiniteMagnitude
var maxY = -CGFloat.greatestFiniteMagnitude
var minX = CGFloat.greatestFiniteMagnitude
var maxX = -CGFloat.greatestFiniteMagnitude
As you collect points from your user, if the x
coordinate is < minX
, update minX
. If it's > maxX
, update maxX
. Do the same for minY
and maxY
.
Once you have maximum and minimum values for x
and y
it's trivial to convert those values to a bounding rectangle. Some sample code:
extension CGRect {
init(minX: CGFloat,
minY: CGFloat,
maxX: CGFloat,
maxY: CGFloat) {
self.init()
origin = CGPoint(x: minX, y: minY)
size = CGSize(width: maxX - minX, height: maxY - minY)
}
}
let aMinX: CGFloat = CGFloat(Int.random(in: 0...50))
let aMinY: CGFloat = CGFloat(Int.random(in: 0...50))
let aMaxX: CGFloat = CGFloat(Int.random(in: 60...200))
let aMaxY: CGFloat = CGFloat(Int.random(in: 60...200))
let aRect: CGRect = CGRect(minX: aMinX,
minY: aMinY,
maxX: aMaxX,
maxY: aMaxY)
print(aRect)