With Love: Bézier
A Bézier curve, named after Bézier Pierre himself, who was a Renault designer in the ’60s, has developed a new way to explain a curvature between two points. Nowadays it has different applications even outside of the automobile industry as it's such a neat way to draw a curved controlled line.
What is the Bézier curve?
Bézier curve is a line between two points (anchor points) and control points that are pulling the line to create the curvature. We have two types of Bézier curves: quadratic curve and cubic curve. A quadratic curve is a curve between two anchor points and one control point. The control point is the reason why the line is curved. Basically, the line is pulled towards the control point. The cubic curve is the same as quadratic, the only difference is that instead of one control point here we have two — which means we can design a more complex curvature. Here is an example of a cubic curve.
You can see from the above, that the curve is affected by the control points — more like they have their own gravity and affecting the curve. X1 and X2 are the anchor points, and C1 and C2 are control points. By changing the position of the control points we can control the curvature. In this example, we are going to put an accent on the cubic Bézier curve, as they are more common compared to the quadratic ones, and have more real-life applications.
Drawing cubic Bézier curve
In Android, we have ready-to-use functions for drawing Bézier — quadraticBezierTo() and cubicTo(). In order to get access to it, we need to instantiate a Path.
In the above snippet, we can see that we are instantiating Path. Within the Path, we are calling moveTo which actually will be our starting point (x1 in the example above). cubicTo() method is the one of our interest here. It's taking 6 float parameters — the first two are the x and y position of the first control point (c1), 3th and 4th are the position of the second control point (c2) and the last two are actually the position of the endpoint (x2).
To draw the path, we just need to call the drawPath method inside the canvas, as so:
For the drawPath parameters, we are just passing our path along with the color and the styling of the line, which in our case is a stroke with 2dp width.
Playground
Since the topic is quite simple and there is not much we can say about it without some real-world use cases, I am going to create a playground app, where you will be able to control all of the points. Even though it's simple we often find ourselves in a situation where we need to connect two objects/lines with a curve. The last time I have used it is quite some time ago when I worked on a custom bottom navigation bar, where I wanted to have it kind of squashed/curved in the middle creating just enough room for the FAB.
I have tried to comment the code as much as possible, but still, if there is anything or if you have any suggestions please leave a comment.
Thank you ❤