kAiN
kAiN

Reputation: 2773

Custom iOS ChartBar

I need your help ... I'm working on my bar graph entirely built by but am having a very big problem ...

As you can see from the photo I have the X-axis that contains the value manually inserted through an array and the Y axis which also contains the different values he entered, as for the X axis, manually through another array.

enter image description here

Now the graph works perfectly but with values from 0 to 100. The code I used for the calculation is this:

 for (NSInteger i = 0; i < self.valueXForBar.count; i++ ) {

        // Assegna lo spazio tra una barra e l'altra //
        CGFloat spaceBetweenBar = 25;

        // Assegna la distanza tra ASSE Y e BARRE //
        CGFloat xPaddingFromYAxis = 15;

        // Assegna la posizione di partenza delle Barre sull'origine Y //
        CGFloat yBarPosition = self.frame.size.height;

        // Sono i valori inseriti nell'array /100 per ogni barra //
        CGFloat index = [[self.valueXForBar objectAtIndex:i] floatValue] /100 ;

        // Larghezza delle barre //
        CGFloat barWidth = 20;

        UIBezierPath *path = [UIBezierPath bezierPath];
        [path moveToPoint:CGPointMake(xPaddingFromYAxis +spaceBetweenBar *i,yBarPosition -25 )];
        [path addLineToPoint:CGPointMake(xPaddingFromYAxis +spaceBetweenBar *i,(yBarPosition -25) - yBarPosition *index)];

        CAShapeLayer *pathLayer = [CAShapeLayer layer];
        pathLayer.frame = self.scrollChart.bounds;
        pathLayer.path = path.CGPath;
        pathLayer.strokeColor = self.fillBarColor.CGColor;
        pathLayer.fillColor = nil;
        pathLayer.lineWidth = barWidth;
        pathLayer.lineJoin = kCALineJoinBevel;
        [self.scrollChart.layer addSublayer:pathLayer];

        CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        pathAnimation.duration = 1;
        pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
        pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
        [pathLayer addAnimation:pathAnimation forKey:@"strokeEnd"];

    }

Now my problem is that the X-axis value added nell'arrayX must match the value entered in Axis Y. To make you understand, the picture I posted the first bar rises up to 18/100 but I wish that the bar (18) corresponded to the value of the axis (18) Y and not the value 18/100

Can you help me figure out how to set this work?

Upvotes: 0

Views: 38

Answers (1)

Luca Davanzo
Luca Davanzo

Reputation: 21520

Are simply proportions:

18 : y = maxY : 100

Where maxY is your max Y-value on chart, in this case 30.

so your y will be:

y = (18 * 100) / maxY

Update

  • Calculate containerHeight as gap between label30-top and label18-bottom.
  • Then calculate height for each item of histogram:

    for value in values {
       h = value * 100 / containerHeight
    }
    

Upvotes: 1

Related Questions