Line Graph

iOS Dev
3 min readOct 17, 2019

Hey all. Today we are going to create line graph with kind of progress animation.

Line Graphic

Looks pretty awesome and could be useful in some apps to show statistic info. I want to share with you some tricks which help you to make this graph in a few steps. So lets start.

Create a new swift project like always. Add a button and a view(I called it graphView and colored orange just for visability).

Next step is create the graph. And layers help me here. First In viewDidLoad add background line.

Here it is, my oldschool color background.

Background layer

Next add animatable layer.

Animatable layer pretty looks like background layer but has couple differences. StrokeEnd is 0 for animation and strokeColor is orange. So in the “start” button action add code for animation:

At that moment the graph looks like that:

Animatable layer

So we are close to the most interesting part. How to convert that orange line to the real graph? With magic and gradient. Gradient has ability makes borders between lines sharp without smooth transition. It’s very useful here.

Look at the gradient’s colors and locations settings. For creating borders sharp next color location has to start with the same location of the previous color. For example, if you want use two colors locations it will be like [0, 0.2,0.2,1]. And colors have to repeated for the each location step. For instance, for location [0, 0.2,0.2,1] colors array will be [red, red, yellow, yellow]. I need horizontal colors position so I set start and end point accordingly. Our current result on a picture below.

Gradient Layer

Looks nice. Almost done. The last step to mix our gradient and graph line. Do it with a mask. Add orange view as the mask for gradient. And that’s it. Done.

Line Graph

Awesome. I hope this information could be useful for you. Have a nice day.

--

--