Android: Draw Equilateral Triangle Shapes In Canvas

I have to admit, you need to dig in a little Math here. Drawing an equilateral triangle in a Canvas is possible using a Path object or use vertices to set up the 3 points.

However, to do automatic calculation, the best possible way to do this would be to either input 2 points and have the method calculate the 3rd point. In my case, I was able to create a method using only 1 point and specifying the distance.

Remember, an equilateral triangle has the same length on all 3 sides so my method’s other parameter entails having to declare the size per side.

And I was able to make a method where the middle point will be calculated depending on the desired location of the developer.

This is the result of the triangle that the method generates. It returns a Path object where, depending on the direction that you choose will point to that direction.

You may notice there is a 3rd parameter of type Direction. It is just an enum class that I created. You can change it if you want. But if you want to use the same class, here is the code for the Direction enum class.

If you want to create a triangle that faces downward like in the 3rd image above with the number 9, you can do it like this.

Related Posts Plugin for WordPress, Blogger...

5 comments

  1. thnk you for such a nice work.. But My problem is that I m using it into my custom linear layout implemented class. And i m using canvas.drawPath(path, p); inside ondraw mwthod. i m calling invalidate() method but still it not working for me. it not showing my triangles… Need help…

Leave a Reply

Your email address will not be published. Required fields are marked *