Share the post "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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public static Path getEquilateralTriangle(Point p1, int width, Direction direction) { Point p2 = null, p3 = null; if (direction == Direction.NORTH) { p2 = new Point(p1.x + width, p1.y); p3 = new Point(p1.x + (width / 2), p1.y - width); } else if (direction == Direction.SOUTH) { p2 = new Point(p1.x + width,p1.y); p3 = new Point(p1.x + (width / 2), p1.y + width); } else if (direction == Direction.EAST) { p2 = new Point(p1.x, p1.y + width); p3 = new Point(p1.x - width, p1.y + (width / 2)); } else if (direction == Direction.WEST) { p2 = new Point(p1.x, p1.y + width); p3 = new Point(p1.x + width, p1.y + (width / 2)); } Path path = new Path(); path.moveTo(p1.x, p1.y); path.lineTo(p2.x, p2.y); path.lineTo(p3.x, p3.y); return path; } |
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.
|
1 2 3 |
public enum Direction { NORTH, SOUTH, EAST, WEST; } |
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.
|
1 2 3 4 5 |
Paint p = new Paint(); p.setStyle(Style.FILL); p.setColor(Color.RED); Path path = getEquilateralTriangle(point, width, Direction.SOUTH); canvas.drawPath(path, p); |
Nice work.. Came in handy for me.. 🙂
Thanks for the tip, I didn’t want to have to use vertex shaders and openGL just to draw a triangle!
@chris: so true!
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…
@nilkash: the problem could be your point object’s coordinates.