How do I implement snap to grid functionality for a UIImageView?
I have a draggable view that I have set up with the following code:
#import <UIKit/UIKit.h>
@interface DraggableView : UIImageView {
CGPoint startLocation;
}
@end
#import "DraggableView.h开发者_开发问答"
@implementation DraggableView
- (id) initWithImage: (UIImage *) anImage
{
if (self = [super initWithImage:anImage])
self.userInteractionEnabled = YES;
return self;
}
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
// Calculate and store offset, and pop view into front if needed
CGPoint pt = [[touches anyObject] locationInView:self];
startLocation = pt;
[[self superview] bringSubviewToFront:self];
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
// Calculate offset
CGPoint pt = [[touches anyObject] locationInView:self];
float dx = pt.x - startLocation.x;
float dy = pt.y - startLocation.y;
CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy);
// Set new location
self.center = newcenter;
}
How do I go about snapping this view to a grid? From a broad viewpoint, I understand that I could offset the new location in a touchesEnded method call. However, I am hitting a brick wall when I try to implement this.
Thanks in advance for any assistance with this issue.
In touchesMoved
, before applying newcenter
to your view, round it to your grid step size:
float step = 10.0; // Grid step size.
newcenter.x = step * floor((newcenter.x / step) + 0.5);
newcenter.y = step * floor((newcenter.y / step) + 0.5);
This will cause your view to "snap" as you drag it.
although the code in jnic's answer is semantically equivalent to the code below, i think this code is more elegant.
here it is in pseudocode (javaish)
int gridCubeWidth = 3; //for instance
int gridCubeHeight = 3;
int newX = Math.Round(oldX / gridCubeWidth) * gridCubeWidth;
int newY = Math.Round(oldY / gridCubeHeight) * gridCubeHeight;
using this example, a point on x like x=4 should map to 3 but x=5 should map to 6.
精彩评论