Search code examples
iphoneiosipadcore-animationcashapelayer

How to plot a graph with CAShapeLayer?


Is it possible to draw just a curve with a given line width using CAShapeLayer? It seems it can only draw filled shapes. I want to draw an animated plot graph. Just a line, not a shape.


Solution

  • Well it seems you can in fact draw lines with CAShapeLayers. Try something like this:

    UIBezierPath *graphPath = [UIBezierPath bezierPath];
    [graphPath moveToPoint:CGPointMake(x, y)];
    [graphPath addLineToPoint:CGPointMake(x, y + h)];
    [graphPath closePath];
    

    Then put it in a CAShapeLayer:

    CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
    [shapeLayer setFrame: aFrame];
    [shapeLayer setPath: [graphPath CGPath]];
    [shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]];
    [shapeLayer setMasksToBounds:YES];
    

    You can change graphPath to plot any curve/line you want to graph.

    Hope this helps!