Skip to content

Instantly share code, notes, and snippets.

@simonbromberg
Created August 4, 2022 16:45
Show Gist options
  • Save simonbromberg/9c9295a88f2b91ea846723fd26293078 to your computer and use it in GitHub Desktop.
Save simonbromberg/9c9295a88f2b91ea846723fd26293078 to your computer and use it in GitHub Desktop.
Move the origin of a CGRect to fit inside a parent rect by capping its edges — eg make sure a child rect does not get drawn out of bounds
extension CGRect {
mutating func moveOriginToFitIn(_ rect: CGRect) {
origin = .init(
x: min(
max(rect.minX, minX),
rect.maxX - width
),
y: min(
max(rect.minY, minY),
rect.maxY - height
)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment