Swift Swift - 5 months ago 24
Swift Question

How to snap-to-grid in macOS via Swift?

I'm developing simple app for macOS using Swift 2. How can I snap a CGPoint to grid (5-pixel distance for example) pressing a keyboard shortcut? I need such kind of point snapping as it's found in AutoCAD.

I am looking for a solution for final project not Interface Builder.


this is the general way to do it, something like a pseudo code

var gridWidth = 16.0
var gridHeight = 16.0

object.Position.X = Math.Floor(object.Position.X / gridWidth) * gridWidth
object.Position.Y = Math.Floor(object.Position.Y / gridHeight) * gridHeight