从每条路径与起始点相距一段距离的点绘制路径

时间:2019-03-13 20:06:09

标签: java android canvas path point

尝试找出如何从画布上的某个点绘制路径时遇到麻烦,每个路径的起点与起始点的距离相等。为了说明我的意思,到目前为止,我拥有的代码可以生成以下内容:enter image description here

期望的结果是这样的:

enter image description here

我的代码:

int n = 3;
int r;
double x;
double y;
point1 = new Point(mWidth/2, mHeight/2);
double angle;
double angleFactor;

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    for (int i = 0; i < 3; i++){
        angleFactor = 2 * Math.PI / n;
        angle = i * angleFactor;
        x = (point1.x) + r * Math.cos(angle);
        y = (point1.y) + r * Math.sin(angle);

        //Draw paths
        path.reset();
        path.moveTo(point1.x, point1.y);
        path.lineTo((float) x, (float) y);
        canvas.drawPath(path, paint);
    }

}

有一个简单的解决方案吗?

1 个答案:

答案 0 :(得分:1)

由于您希望线的偏移量和中心点之间的距离很小,因此可以这样定义起始坐标:

double xStart, xEnd;
double yStart, yEnd;
double offsetFraction = 0.1;

for中的onDraw()循环内:

double lengthX = r * Math.cos(angle);
double lengthY = r * Math.sin(angle);

xStart = (point1.x) + offsetFraction * lengthX;
yStart = (point1.y) + offsetFraction * lengthY;
xEnd = (point1.x) + lengthX;
yEnd = (point1.y) + lengthY;

//Draw paths
path.reset();
path.moveTo((float) xStart, (float) yStart);
path.lineTo((float) xEnd, (float) yEnd);
canvas.drawPath(path, paint);