触摸坐标比较(Comparing Touch Coordinates)

2019-08-18 05:33发布

是否有可能触摸坐标通过UIView的用户进行的比较中的plist或txt格式的一个店? 这个论点看起来是这样的;

  if (user touch coordinate == touch coordinate stored in plist or text)
  then
    (do something)
  else
    (do something)

如果可能的话以何种格式我应该写在列表中的坐标,如何将它里面的程序相关联?

在此先感谢和抱歉,如果你发现我的问题有点noobie。

Answer 1:

不知道是否有一个班轮解决方案。

上的UITouch例如, locationInView:方法返回一个CGPoint结构(x和y坐标,两者float类型)。 所以,你可以存储在你的plist中的X和Y坐标,然后将它们与当前触摸的X和Y坐标进行比较。

编辑:另外,在比较的坐标时,你可能想使用的距离两点之间,以确定当你有一个“打”。

编辑:下面是加载和写入一个属性列表,其中的值是基于NSDictionary的代码示例:

- (NSMutableDictionary *)loadDictionaryFromPList: (NSString *)plistName
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
    NSDictionary *immutableDictionary = [NSDictionary dictionaryWithContentsOfFile: plistPath];
    NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary: immutableDictionary];
    return mutableDictionary;
}


- (void)saveDictionary: (NSDictionary *)mySettings toPList: (NSString *)plistName
{
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
    [mySettings writeToFile: plistPath atomically: YES];
}

的方法来计算UITouches的两个位置之间的距离:

-(CGFloat) distanceBetween: (CGPoint) point1 and: (CGPoint)point2
{
    CGFloat dx = point2.x - point1.x;
    CGFloat dy = point2.y - point1.y;
    return sqrt(dx*dx + dy*dy );
}

最后,使用该值在属性列表中的代码,以确定用户是否击中了前面的位置:

CGPoint currentTouchLocation = [currentTouch locationInView:self];

// Lookup last Touch location from plist, and handle case when current Touch matches it:
NSMutableDictionary *mySettings = [self loadDictionaryFromPList: @"MySettings"];
NSNumber *lastXCoordinate = [mySettings objectForKey:@"lastXCoordinate"];
NSNumber *lastYCoordinate = [mySettings objectForKey:@"lastYCoordinate"];
if (lastXCoordinate && lastYCoordinate)
{
    CGPoint lastTouchLocation = CGPointMake([lastXCoordinate floatValue], [lastYCoordinate floatValue]);
    CGFloat distanceBetweenTouches = [self distanceBetween: currentTouchLocation and: lastTouchLocation];
    if (distanceBetweenTouches < 25) // 25 is just an example
    {
        // Handle case where current touch is close enough to "hit" previous one
        NSLog(@"You got a hit!");
    }
}

// Save current touch location to property list:
[mySettings setValue: [NSNumber numberWithFloat: currentTouchLocation.x] forKey: @"lastXCoordinate"];
[mySettings setValue: [NSNumber numberWithFloat: currentTouchLocation.y] forKey: @"lastYCoordinate"];
[self saveDictionary:mySettings toPList: @"MySettings"];


Answer 2:

你可能寻找的功能是NSStringFromCGPoint()CGPointFromString()

但有两个触点座标几乎肯定会永远是完全相同的。 你应该几乎从不进行比较CGFloats== ,更不用说那些你从这样的模拟输入作为一个手指触摸得到。 你需要比较它们是否“足够接近”。 见本博客为如何测量两点之间的距离,一个很好的例子。 你想要的结果小于某一值(ε,或“少数”),是适合你的目的。



文章来源: Comparing Touch Coordinates