Search code examples
androidmathgraphicsdrawingdraw

Android How to draw triangles inside a hexagon?


First thing I have drawn the three lines of the hexagon width specific width then I have drawn the six points using this formula section = 2 * PI / NumberOfPoints. Here is the pic of lines I have drawn:

what I want is to draw a triangle between every two lines which will be 6 triangles. Here is the pic when I drew the triangles:

My problem is I want the triangle to be drawn between the lines, not above them which mean the triangle should not overlaps the line.

Here is how I drew the lines:

 for (int i = 1; i <= 6; i++) {

        float eX = (float) (x + radius * Math.cos(section * i));

        float eY = (float) (y + radius * Math.sin(section * i));

        linesPaint.setShader(new LinearGradient(x, y, eX, eY, Color.BLACK, Color.TRANSPARENT, Shader.TileMode.MIRROR));

        canvas.drawLine(x, y, eX, eY, linesPaint);

    }

and here is how I drew the triangles

 for (int i = 1; i <= 6; i++) {

        TriangleColor triangleColor = triangleColors.get(i - 1);

        trianglesPaint.setShader(new LinearGradient(0, 0, 0, getHeight(), triangleColor.firstColor, triangleColor.secondColor, Shader.TileMode.REPEAT));

        float x1 = (float) (x + radius * Math.cos(section * i));

        float y1 = (float) (y + radius * Math.sin(section * i));

        float x2 = (float) (x + radius * Math.cos(section * (i + 1)));

        float y2 = (float) (y + radius * Math.sin(section * (i + 1)));

        trianglesPath.moveTo(x, y);

        trianglesPath.lineTo(x1, y1);

        trianglesPath.lineTo(x2, y2);

        trianglesPath.lineTo(x, y);

        canvas.drawPath(trianglesPath, trianglesPaint);

        trianglesPath.reset();
    }

Can anyone help me with the formula? Thanks in advance.


Solution

  • I assume that you have lines with thickness 2d

    To avoid overwriting these lines, you can shift the central point for every triangle by dstance d/sin(30) = 2*d in direction of bisector between two lines

    Perhaps also you need to diminish radius (length of triangle side along the line)

    newradius = radius - d*sqrt(3) - d * sqrt(3)/3 
    

    enter image description here

    for (int i = 1; i <= 6; i++) {
    
        cx = x + 2 * d * Math.cos(section * (i + 0.5));
        cy = x + 2 * d * Math.sin(section * (i + 0.5));
    
        float x1 = (float) (cx + newradius * Math.cos(section * i));  /
        //and similar  for other coordinates
    
        trianglesPath.moveTo(cx, cy);
    
        trianglesPath.lineTo(x1, y1);
        ...