I recently created a small demo app drawing various shapes, including triangles, rectangles and spirals. Here is the code for drawing the triangles. For full context, reference the project. In this app, the user can draw a triangle as a single drawing or a composition of two triangles forming into one as the user scrolls. The increasing triangle growth is accomplished through the principles of Triangle Similarity, with each smaller triangle similar to the large triangle in the end.
Project: https://github.com/jdgreene2008/android_custom_views
Source Excerpt: https://github.com/jdgreene2008/android_custom_views/blob/master/CustomUiComponents/app/src/main/java/com/jarvis/dragdropresearch/views/FlashShapeView.java
private void drawTriangleShape(Canvas canvas, RectF bounds,
TriangleInterpolator triangleInterpolator, Paint paint) {
paint.setStyle(Paint.Style.FILL);
float baseInterpolation = triangleInterpolator
.getInterpolatedValues()[TriangleInterpolator.INTERPOLATION_VALUES_BASE];
float altitudeInterpolation = triangleInterpolator
.getInterpolatedValues()[TriangleInterpolator.INTERPOLATION_VALUES_ALTITUDE];
// *** Construct the Left Triangle ** //
// Bottom left vertex
float bottomLeftX = bounds.left;
float bottomLeftY = bounds.bottom;
// Bottom right corner
float bottomRightX = bottomLeftX + baseInterpolation;
float bottomRightY = bounds.bottom;
//Top Vertex
float topX = bottomRightX;
float topY = bottomRightY - altitudeInterpolation;
Path leftTriangle = new Path();
leftTriangle.lineTo(bottomLeftX, bottomLeftY);
leftTriangle.lineTo(bottomRightX, bottomRightY);
leftTriangle.lineTo(topX, topY);
leftTriangle.lineTo(bottomLeftX, bottomLeftY);
canvas.drawPath(leftTriangle, paint);
if (triangleInterpolator.isSymmetric()) {
// *** Construct the Right Triangle ** //
bottomLeftX = bounds.right - baseInterpolation;
bottomLeftY = bounds.bottom;
bottomRightX = bounds.right;
bottomRightY = bounds.bottom;
topX = bottomLeftX;
topY = bottomRightY - altitudeInterpolation;
Path rightTriangle = new Path();
rightTriangle.lineTo(bottomLeftX, bottomLeftY);
rightTriangle.lineTo(bottomRightX, bottomRightY);
rightTriangle.lineTo(topX, topY);
rightTriangle.lineTo(bottomLeftX, bottomLeftY);
canvas.drawPath(rightTriangle, paint);
}
}