如何为UIImageView实现对齐网格功能?

时间:2011-03-24 15:28:01

标签: objective-c ios4 uiimageview draggable

我有一个可拖动的视图,我已使用以下代码进行设置:

#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方法调用中偏移新位置。但是,当我尝试实现这个时,我正在碰壁砖。

提前感谢您对此问题的任何帮助。

2 个答案:

答案 0 :(得分: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);

这会导致您的视图在拖动时“捕捉”。

答案 1 :(得分: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 = 4的x上的点应映射到3,但x = 5应映射到6。