I have write following code to show bar plot annotation. Annotations are shown but with unexpected alignment/position. Text of CPTextLayer is showing at top-left corner of the frame. I am trying to show it at center. I have used a background image of the CPTextLayer as background color. Please have a look through the code- (symbolTextAnnotation is a CPLayerAnnotation object decleared in the interface)
-(void)barPlot:(CPBarPlot *)plot barWasSelectedAtRecordIndex:(NSUInteger)index
{
CPXYGraph* graph = (CPXYGraph*)plot.graph;
NSNumber *value = [self numberForPlot:plot field:CPBarPlotFieldBarTip recordIndex:index];
if ( symbolTextAnnotation ) {
[graph.plotAreaFrame.plotArea removeAnnotation:symbolTextAnnotation];
symbolTextAnnotation = nil;
}
// Setup a style for the annotation
CPMutableTextStyle *hitAnnotationTextStyle = [CPMutableTextStyle textStyle];
hitAnnotationTextStyle.color = [CPColor whiteColor];
hitAnnotationTextStyle.fontSize = 9.0f;
hitAnnotationTextStyle.fontName = @"Helvetica-Bold";
// Determine point of symbol in plot coordinates
NSNumber *x = [NSNumber numberWithInt:index+1];
NSNumber *y = [NSNumber numberWithInt:0];
NSArray *anchorPoint = [NSArray arrayWithObjects:y, x, nil];
// Add annotation
// First make a string for the y value
NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setMaximumFractionDigits:2];
NSString *yString = [formatter stringFromNumber:value];
// Now add the annotation to the plot area
UIImage *annotationBG = [UIImage imageNamed:@"annotation-bg.png"];
CPTextLayer *textLayer = [[[CPTextLayer alloc] initWithText:yString style:hitAnnotationTextStyle] autorelease];
textLayer.backgroundColor = [UIColor colorWithPatternImage:annotationBG].CGColor;
textLayer.frame = CGRectMake(0, 0, annotationBG.size.width, annotationBG.size.height);
symbolTextAnnotation = [[CPPlotSpaceAnnotation alloc] initWithPlotSpace:plot.plotSpace anchorPlotPoint:anchorPoint];
symbolTextAnnotation.contentLayer = textLayer;
symbolTextAnnotation.displacement = CGPointMake(-18.0f, 3.0f);
[graph.plotAreaFrame.plotArea addAnnotation:symbolTextAnnotation];
}
CPTextLayersizes itself to the size of its text. Resizing it after setting the text is causing the drawing problem. You could make another CPLayer, set your background on that, make your CPTextLayer a sublayer, and position it however you want.The
displacementproperty works with thecontentAnchorPointproperty to position the annotation. The contentAnchorPoint is the Core Animation anchor point for your content layer. The displacement is the pixel offset of that point from the anchorPlotPoint of the annotation. For example, if you want your annotation centered at the anchorPlotPoint, set the contentAnchorPoint toCGPointMake(0.5, 0.5)and the displacement toCGPointZero.