I stuck in plotting annotation inside the graph. The annotation is coming exactly at the respective x coordinate but its Y coordinate is not alining properly it is showing some where at the top where as i need annotation placed exactly at the tapped position.
-(void)scatterPlot:(CPTScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)idx {
UIView *view = [self.graphView.superview viewWithTag:99];
if (view!=nil) {
[view removeFromSuperview];
}
NSNumber *plotXvalue = [self numberForPlot:plot field:CPTScatterPlotFieldX recordIndex:idx];
NSNumber *plotYvalue = [self numberForPlot:plot field:CPTScatterPlotFieldY recordIndex:idx];
NSArray *anchorPoint = [NSArray arrayWithObjects:plotXvalue, plotYvalue, nil];
CPTGraph *graph = self.hostView.hostedGraph;
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
CGPoint cgPlotPoint = CGPointMake(plotXvalue.floatValue, plotYvalue.floatValue);
CGPoint cgPlotAreaPoint = [graph convertPoint:cgPlotPoint toLayer:self.graphView.layer];
NSDecimal plotAreaPoint[2];
plotAreaPoint[CPTCoordinateX] = CPTDecimalFromFloat(cgPlotAreaPoint.x);
plotAreaPoint[CPTCoordinateY] = CPTDecimalFromFloat(cgPlotAreaPoint.y);
CPTLayer *layer = [[CPTLayer alloc] init];
layer.contents = (id)view;
CGPoint dataPoint = [plotSpace plotAreaViewPointForPlotPoint:plotAreaPoint numberOfCoordinates:2];
NSLog(@"datapoint (CGPoint) coordinates tapped: %@",NSStringFromCGPoint(dataPoint));
if ([self.graphView.superview viewWithTag:99]) {
[[self.graphView.superview viewWithTag:99] removeFromSuperview];
}
//CGRect graphFrame = self.graphView.frame;
//A View To add Image And Annotation
UIView *selectedPointdetails = [[UIView alloc] initWithFrame:CGRectMake(dataPoint.x,dataPoint.y, 38.0, 27.0)];
selectedPointdetails.tag = 99;
UIImageView *annotationImage = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, selectedPointdetails.frame.size.width, selectedPointdetails.frame.size.height)];
annotationImage.image = [UIImage imageNamed:@"[email protected]"];
[selectedPointdetails addSubview:annotationImage];
UILabel *annotationValue = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 38.0, 20.0)];
annotationValue.textColor = [UIColor whiteColor];
annotationValue.textAlignment = NSTextAlignmentCenter;
annotationValue.text = [NSString stringWithFormat:@"%0.2f",[plotYvalue floatValue]];
NSLog(@"plotYvalue %@", plotYvalue);
annotationValue.font = [UIFont fontWithName:nil size:10.0];
[selectedPointdetails addSubview:annotationValue];
[self.graphView.superview addSubview:selectedPointdetails];
[self.graphView.superview bringSubviewToFront:selectedPointdetails];
}
The
dataPoint
received from the plot space is in the coordinate space of the plot area layer. Convert it to the graph layer coordinates which also match the hosting view coordinates. From there, convert it to the parent view's coordinate space and use that point to anchor your label.