2011-03-24 23 views
2

我有一个可拖动的观点,我已经设置了用下面的代码:如何实现捕捉UIImageView的网格功能?

#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; 
} 

如何去捕捉这种观点的电网?从广泛的角度来看,我知道我可以在touchesEnded方法调用中抵消新位置。但是,当我试图实现这一点时,我碰到了一堵砖墙。

在此先感谢您对此问题的任何帮助。

回答

11

touchesMoved,应用newcenter到您的视图,圆到您的网格步长之前:

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); 

这将导致您的视图“嵌入”当你拖动。

4

尽管jnic的答案中的代码在语义上等同于下面的代码,但我认为这段代码更优雅。

在这里它是在伪代码(javaish)

int gridCubeWidth = 3; //for instance 
int gridCubeHeight = 3; 

int newX = Math.Round(oldX/gridCubeWidth) * gridCubeWidth; 
int newY = Math.Round(oldY/gridCubeHeight) * gridCubeHeight; 

使用此实例中,X上的一个点状X = 4应映射到3,但是X = 5应映射到6