Snap to grid effect with Quartz 2d? iphone dev

我怕爱的太早我们不能终老 提交于 2019-12-04 19:19:41

Assuming that your approach is to let the user tap, and then put the pin at the closest grid intersection, this is basically just a rounding problem.

// assume these constants
// kVGridOffset, kHGridOffset: the difference between the origin of the view
//   and the origin of the grid
// kVGridSpacing, kHGridSpacing: the size of the grid itself

// set initial coordinates from touch
CGPoint drawPoint = CGPointMake(lastTouch.x - horizontalOffset, lastTouch.y - verticalOffset);

// remove the offset, round to nearest increment of spacing, and return offset
drawPoint.x = floor((drawPoint.x - kHGridOffset) / kHGridSpacing + 0.5) * kHGridSpacing + kHGridOffset;
drawPoint.y = floor((drawPoint.y - kVGridOffset) / kVGridSpacing + 0.5) * kVGridSpacing + kVGridOffset;

// draw the image
[drawImage drawAtPoint:drawPoint];

EDIT: with the availability of nearbyint() for rounding, things can be a little neater:

drawPoint.x = nearbyint((drawPoint.x - kHGridOffset) / kHGridSpacing) * kHGridSpacing + kHGridOffset;
drawPoint.y = nearbyint((drawPoint.y - kVGridOffset) / kVGridSpacing) * kVGridSpacing + kVGridOffset;

You'll need some kind of data structure that represents the grid in your view controller. Maybe it'll contain an array of coordinates, each representing where the vertical and horizontal lines cross.

Then when you touch the view, you compare the y value with all the y values in your grid structure, and choose the one that is closest. Same for the x value. That should give the idea of a snap to grid.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!