Базовый график CPTextLayer: выравнивание текста с фоновым изображением в качестве цвета фона - PullRequest
2 голосов
/ 04 мая 2011

Я написал следующий код, чтобы показать аннотацию гистограммы. Аннотации показаны, но с неожиданным выравниванием / положением. Текст CPTextLayer отображается в верхнем левом углу рамки. Я пытаюсь показать это в центре. Я использовал фоновое изображение CPTextLayer в качестве цвета фона. Пожалуйста, просмотрите код- (symbolTextAnnotation является объектом CPLayerAnnotation, объявленным в интерфейсе)

-(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];    
}

1 Ответ

3 голосов
/ 05 мая 2011

CPTextLayer масштабируется до размера его текста.Изменение размера после установки текста вызывает проблемы с рисованием.Вы можете создать еще один CPLayer, установить на нем свой фон, сделать свой CPTextLayer подслойом и расположить его так, как вам удобно.

Свойство displacement работает со свойством contentAnchorPoint для позиционирования аннотации.ContentAnchorPoint является базовой точкой анимации для вашего слоя контента.Смещение - это пиксельное смещение этой точки от anchorPlotPoint аннотации.Например, если вы хотите, чтобы ваша аннотация центрировалась в anchorPlotPoint, установите для contentAnchorPoint значение CGPointMake(0.5, 0.5), а для смещения - CGPointZero.

...