objective-c - 如何实现 UIImageView 的对齐网格功能?

标签 objective-c ios4 uiimageview draggable

我有一个可拖动的 View ,我使用以下代码设置了它:

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

如何将此 View 捕捉到网格?从广泛的角度来看,我知道我可以在 TouchsEnded 方法调用中偏移新位置。然而,当我尝试实现这一点时,我遇到了困难。

预先感谢您提供有关此问题的任何帮助。

最佳答案

touchesMoved 中,在将 newcenter 应用到 View 之前,将其舍入为网格步长:

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

这将导致您的 View 在拖动时“对齐”。

关于objective-c - 如何实现 UIImageView 的对齐网格功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5421566/

相关文章:

iphone - iOS4.0 iphone应用程序在后台运行时AudioQueueStart失败

objective-c - 获取 iPhone 上已安装的应用程序列表

objective-c - UIImageVIew 中的 UIScrollView 中的 UIImage

iphone - 对 Objective-c 对象数组进行排序

iphone - sudzc 生成错误的 soap 请求

iphone - cocos2d : playing a video in the background of a menu

iphone - 日期更改后的 UIDatePicker

debugging - 什么是 “Interface Builder Cocoa Touch Tool”

ios - 如何从 iOS 中的 ImageView 获取标签?

iphone - 触摸移动时如何检测 ImageView 的触摸结束