首页 > 解决方案 > Android 如何在六边形内绘制三角形?

问题描述

首先,我绘制了六边形宽度特定宽度的三条线,然后使用此公式绘制了六个点section = 2 * PI / NumberOfPoints。这是我画的线条图片:

我想要的是在每两条线之间画一个三角形,这将是 6 个三角形。这是我画三角形时的照片:

我的问题是我希望在线条之间绘制三角形,而不是在它们上方,这意味着三角形不应与线条重叠。

这是我画线的方式:

 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);

    }

这是我画三角形的方法

 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();
    }

任何人都可以帮我计算公式吗?提前致谢。

标签: androidmathgraphicsdrawingdraw

解决方案


我假设你有粗线条2d

d/sin(30) = 2*d为避免覆盖这些线,您可以在两条线之间的平分线方向上移动每个三角形的中心点

也许您还需要减小半径(沿线的三角形边的长度)

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

在此处输入图像描述

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);
    ...

推荐阅读