核心绘图CPTextLayer:文本与背景图像对齐作为背景颜色
问题描述:
我写下面的代码来显示条形图注释。显示注释但出现意外的对齐/位置。 CPTextLayer的文本显示在框架的左上角。我试图在中心展示它。我已经使用CPTextLayer的背景图像作为背景颜色。请有过代码 - 一看(symbolTextAnnotation是在界面decleared一个CPLayerAnnotation对象)核心绘图CPTextLayer:文本与背景图像对齐作为背景颜色
-(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];
}
答
CPTextLayer
尺寸本身的文本的大小。设置文本后调整大小会导致绘图问题。你可以制作另一个CPLayer,设置你的背景,让你的CPTextLayer成为一个子图层,然后根据需要定位它。
displacement
属性与contentAnchorPoint
属性一起使用来定位注释。 contentAnchorPoint是您的内容层的核心动画锚点。位移是该点与注释的anchorPlotPoint的像素偏移量。例如,如果要将注释集中在anchorPlotPoint中,请将contentAnchorPoint设置为CGPointMake(0.5, 0.5)
,并将位移设置为CGPointZero
。
我试过了上面提到的解决方案,但输出是一样的。 – Sadat 2011-05-05 01:42:27
得到了解决方案。感谢您的信息。我已将CPTextLayer添加到CPLayer中,并根据需要为CPLayer设置填充。这对我来说很好。 :) – Sadat 2011-05-05 02:12:26
萨达特,你介意分享你的代码吗?我使用类似的方法,但我看不到任何填充。 – 2012-06-19 12:44:37