【发布时间】:2012-03-19 18:00:12
【问题描述】:
我正在使用 Core Plot 来显示价格的时间序列。当用户触摸图形时,我会在该点显示一条可拖动的垂直线。时间序列和可拖动线都是CPTXYGraph 中的CPTScatterPlot 对象。这很有效 - 将线拖过时间序列图时的性能是可以接受的。
下一阶段是在用户选择的点显示价格和日期。雅虎股票应用程序有一个很好的功能,它可以在一个移动的标签中显示价格,就好像它附在可拖动线的顶部一样。我尝试使用CPTPlotSpaceAnnotation 中显示的文本来复制它。这可行,但会严重影响性能。经过一番挖掘,我发现CPTLayer drawInContext: 被多次调用 - 看起来每次我重绘文本标签时都会重绘整个图表(实际上我的日志暗示它被重绘了两次)。
这是绘制标签的代码(正在进行中)。它被plotSpace:shouldHandlePointingDeviceDraggedEvent:atPoint:调用。
- (void)displayPriceAndDateForIndex:(NSUInteger)index atPoint:(CGPoint)pointInPlotArea
{
NSNumber * theValue = [[self.graphDataSource.timeSeries objectAtIndex:index] observationValue];
// if the annotations already exist, remove them
if ( self.valueTextAnnotation ) {
[self.graph.plotAreaFrame.plotArea removeAnnotation:self.valueTextAnnotation];
self.valueTextAnnotation = nil;
}
// Setup a style for the annotation
CPTMutableTextStyle *annotationTextStyle = [CPTMutableTextStyle textStyle];
annotationTextStyle.color = [CPTColor whiteColor];
annotationTextStyle.fontSize = 14.0f;
annotationTextStyle.fontName = @"Helvetica-Bold";
// Add annotation
// First make a string for the y value
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
NSString *currentValue = [formatter stringFromNumber:theValue];
NSNumber *x = [NSNumber numberWithDouble:[theDate timeIntervalSince1970]];
NSNumber *y = [NSNumber numberWithFloat:self.graphDataSource.maxValue];
NSArray *anchorPoint = [NSArray arrayWithObjects:x, y, nil];
// Then add the value annotation to the plot area
float valueLayerWidth = 50.0f;
float valueLayerHeight = 20.0f;
CPTTextLayer *valueLayer = [[CPTTextLayer alloc] initWithFrame:CGRectMake(0,0,valueLayerWidth,valueLayerHeight)];
valueLayer.text = currentValue;
valueLayer.textStyle = annotationTextStyle;
valueLayer.backgroundColor = [UIColor blueColor].CGColor;
self.valueTextAnnotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:self.graph.defaultPlotSpace anchorPlotPoint:anchorPoint];
self.valueTextAnnotation.contentLayer = valueLayer;
// modify the displacement if we are close to either edge
float xDisplacement = 0.0;
...
self.valueTextAnnotation.displacement = CGPointMake(xDisplacement, 8.0f);
[self.graph.plotAreaFrame.plotArea addAnnotation:self.valueTextAnnotation];
// now do the date field
...
}
完全重绘是预期的行为吗?有没有更好的方法来管理注释而不破坏它并在每次调用方法时重新创建它?
【问题讨论】:
标签: ios cocoa-touch core-plot