2011-05-04 119 views
1

我寫下面的代碼來顯示條形圖註釋。顯示註釋但出現意外的對齊/位置。 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];  
} 

回答

2

CPTextLayer尺寸本身的文本的大小。設置文本後調整大小會導致繪圖問題。你可以製作另一個CPLayer,設置你​​的背景,讓你的CPTextLayer成爲一個子圖層,然後根據需要定位它。

displacement屬性與contentAnchorPoint屬性一起使用來定位註釋。 contentAnchorPoint是您的內容層的核心動畫錨點。位移是該點與註釋的anchorPlotPoint的像素偏移量。例如,如果要將註釋集中在anchorPlotPoint中,請將contentAnchorPoint設置爲CGPointMake(0.5, 0.5),並將位移設置爲CGPointZero

+0

我試過了上面提到的解決方案,但輸出是一樣的。 – Sadat 2011-05-05 01:42:27

+0

得到了解決方案。感謝您的信息。我已將CPTextLayer添加到CPLayer中,並根據需要爲CPLayer設置填充。這對我來說很好。 :) – Sadat 2011-05-05 02:12:26

+0

薩達特,你介意分享你的代碼嗎?我使用類似的方法,但我看不到任何填充。 – 2012-06-19 12:44:37