准确地在点击的右侧绘制注释

时间:2014-11-13 10:35:12

标签: ios objective-c core-plot

我坚持在图表中绘制注释。注释恰好在相应的x坐标上,但是它的Y坐标没有正确显示,它显示了一些位于顶部的位置,因为我需要注释完全位于轻敲位置。

-(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:@"Popup@2x.png"];
    [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];       
}

1 个答案:

答案 0 :(得分:0)

从绘图空间接收的dataPoint位于绘图区域图层的坐标空间中。将其转换为与托管视图坐标匹配的图层图层坐标。从那里,将其转换为父视图的坐标空间,并使用该点来锚定您的标签。