我是核心情节的新手。我试图计算最接近的数据指向下面代码中感应到触摸的坐标:
-(BOOL)plotSpace:(CPTPlotSpace *)space shouldHandlePointingDeviceDownEvent:(id)event atPoint:(CGPoint)point
{
NSLog(@"touch sensed");
NSLog(@"points: %f, %f",point.x,point.y);
[self.distances removeAllObjects];
CPTGraph *graph = self.hostView.hostedGraph;
if (symbolTextAnnotation) {
[graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
symbolTextAnnotation = nil;
}
CPTMutableTextStyle *hitAnnotationTextStyle = [CPTMutableTextStyle textStyle];
hitAnnotationTextStyle.color = [CPTColor whiteColor];
hitAnnotationTextStyle.fontSize = 16.0;
hitAnnotationTextStyle.fontName = @"Helvetica-Bold";
for(int i=0;i<[self.allX count];i++){
//NSLog(@"-->all points: %@, %@", [self.allX objectAtIndex:i],[self.allY objectAtIndex:i]);
NSLog(@"-->all points: %f, %f", [[self.allX objectAtIndex:i] floatValue],[[self.allY objectAtIndex:i] floatValue]);
CGFloat xDist = (point.x - [[self.allX objectAtIndex:i] floatValue]);
CGFloat yDist = (point.y - [[self.allY objectAtIndex:i] floatValue]);
NSLog(@"-->all distances: %f, %f", xDist,yDist);
CGFloat distance = sqrt((xDist * xDist) + (yDist * yDist));
NSNumber *distanceNum = [NSNumber numberWithFloat:distance];
NSLog(@"-->total distance: %@", distanceNum);
[self.distances addObject:distanceNum];
}
for(int i=0;i<[self.distances count];i++){
NSLog(@"calculated distances: %@",[self.distances objectAtIndex:i]);
}
NSNumber *minDistance = [self.distances valueForKeyPath:@"@min.doubleValue"];
NSLog(@"min distance: %@", minDistance);
int index=[self.distances indexOfObject:minDistance];
NSLog(@"cloest point: %@,%@",[self.allX objectAtIndex:index],[self.allY objectAtIndex:index]);
NSArray *anchorPoint = @[[self.allX objectAtIndex:index], [self.allY objectAtIndex:index] ];
CPTTextLayer *textLayer = [[CPTTextLayer alloc] initWithText:@"LABEL" style:hitAnnotationTextStyle] ;
symbolTextAnnotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:graph.defaultPlotSpace anchorPlotPoint:anchorPoint];
symbolTextAnnotation.contentLayer = textLayer;
symbolTextAnnotation.displacement = CGPointMake(0.0, 20.0);
[graph.plotAreaFrame.plotArea addAnnotation:symbolTextAnnotation];
return 1;
}
然而,我刚刚意识到此方法返回的触摸坐标不是在与图表上绘制的坐标相同的系统中测量的。例如,触摸图形上的坐标(2,60)将返回像(188,150)这样的坐标,这些坐标是关闭的。有没有办法在图形坐标系中找到等效的(188,150)?
答案 0 :(得分:0)
使用绘图空间(作为参数传递给此方法)在数据坐标和绘图区域视图坐标之间进行转换。
使用以下方法之一从event
中提取触摸坐标并将其转换为数据坐标。
-(void)plotPoint:(NSDecimal *)plotPoint numberOfCoordinates:(NSUInteger)count forEvent:(CPTNativeEvent *)event;
-(void)doublePrecisionPlotPoint:(double *)plotPoint numberOfCoordinates:(NSUInteger)count forEvent:(CPTNativeEvent *)event;
或者,使用-plotAreaViewPointForEvent:
方法从事件中提取触摸点的视图坐标,并使用以下方法之一将数据坐标转换为视图坐标并计算该坐标系中的距离: / p>
-(CGPoint)plotAreaViewPointForPlotPoint:(NSDecimal *)plotPoint numberOfCoordinates:(NSUInteger)count;
-(CGPoint)plotAreaViewPointForDoublePrecisionPlotPoint:(double *)plotPoint numberOfCoordinates:(NSUInteger)count;