android 五角星画法 五角星计算公式

计算依据,每个五角星的角度为36°,然后根据简单的勾股定理即可算出各个点的坐标,如下图所示
android 五角星画法 五角星计算公式_第1张图片

    /**
     * @param xA 起始点位置A的x轴绝对位置
     * @param yA 起始点位置A的y轴绝对位置
     * @param rFive 五角星边的边长
     */
public static float[] fivePoints(float xA, float yA, int rFive) {
        float xB = 0;
        float xC = 0;
        float xD = 0;
        float xE = 0;
        float yB = 0;
        float yC = 0;
        float yD = 0;
        float yE = 0;
        xD = (float) (xA - rFive * Math.sin(Math.toRadians(18)));
        xC = (float) (xA + rFive * Math.sin(Math.toRadians(18)));
        yD = yC = (float) (yA + Math.cos(Math.toRadians(18)) * rFive);
        yB = yE = (float) (yA + Math.sqrt(Math.pow((xC - xD), 2) - Math.pow((rFive / 2), 2)));
        xB = xA + (rFive / 2);
        xE = xA - (rFive / 2);
        float[] floats = new float[]{xA, yA,  xD, yD,xB, yB, xE, yE, xC, yC,xA, yA};
        return floats;
    }

接下来画线就比较容易了,使用Canvas,Path,Paint就完成了五角星的绘制。

 private Paint mPaint;
 private Path mPath;
 private float xA = 400;
 private float yA = 200;
 private int r = 100; //五角星边长
 ······
 mPaint = new Paint();
 mPaint.setColor(Color.RED);
 mPath = new Path();
 float[] floats = Utils.fivePoints(xA, yA, r);
 for (int i = 0; i < floats.length - 1; i++) {
      mPath.lineTo(floats[i], floats[i += 1]);
 }
 ······
 @Override
 protected void onDraw(Canvas canvas) {
      super.onDraw(canvas);
      canvas.drawPath(mPath, mPaint);
 }

结束。

你可能感兴趣的:(Android-技巧)