0
votes

I have a horizontal bar chart using Coreplot in which I have labels within the bar itself with white text like this

Long Bar

However, when the bar is to short to contain the label I would like the text Black and not offset like this.

Short Bar

Is there anything available to check if the label is clipped or compare the wide of the label to the bar length? So far I have this

-(CPTTextLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index
{
    NSNumberFormatter *numberFormatter = [NSNumberFormatter percentFormatter];
    NSDictionary *bar = [self.dataSource objectAtIndex:index];
    NSDecimalNumber *xValue = [bar valueForKey:@"Value"];
    NSString *stringLabel = [numberFormatter stringFromNumber:xValue];

    CPTMutableTextStyle *whiteStyle = [[CPTMutableTextStyle alloc] init];
    whiteStyle.color    = [CPTColor whiteColor];
    whiteStyle.fontSize = CPTFloat(12.0);
    whiteStyle.fontName = @"HelveticaNeue-Medium";

    CPTMutableTextStyle *darkStyle = [[CPTMutableTextStyle alloc] init];
    darkStyle.color    = [CPTColor blackColor];
    darkStyle.fontSize = CPTFloat(12.0);
    darkStyle.fontName = @"HelveticaNeue-Medium";

    CPTTextLayer *textLayer = [[CPTTextLayer alloc] initWithText:stringLabel];

    if (**isLabelClipped**) {
        plot.labelOffset = 2.0f;
        textLayer.textStyle = darkStyle;
    } else {
        plot.labelOffset = -2.0f;
        textLayer.textStyle = whiteStyle;
    }
    return textLayer;
}

EDIT As Eric suggested I attempted to to get the screen size from the plotspace, my thinking was I would use the difference between the xValue and the barsBase, so I added the following

NSDecimal plotPoint[2];
plotPoint[CPTCoordinateX] = xValue.decimalValue;

NSNumber *barBase = [self numberForPlot:plot
                                     field:CPTBarPlotFieldBarBase
                               recordIndex:index];

plotPoint[CPTCoordinateY] = barBase.decimalValue;
CGPoint dataPoint = [plot.plotSpace plotAreaViewPointForPlotPoint:plotPoint numberOfCoordinates:2];
NSLog(@"Data Point:%@", NSStringFromPoint(dataPoint));

But this gives values like

{531.46951532736807, 57.166666666666664}

The barBase value (57..) looks to be the far left of the plot area and not the 0 axis as expected.

1

1 Answers

1
votes

Knowing the bar length (from the xValue), you can use the plot space to determine its size on screen. After creating the textLayer, check its bounds size. Compare the two and decide whether to position the label inside or outside the bar.