如何在画布上的两个点之间绘制一条曲线? [英] How to draw a curved line between 2 points on canvas?
问题描述
我已经尝试了许多与网络示例不同的方法,但是我似乎无法使其正常工作.我正在尝试制作一种在画布上的2个点之间绘制一条曲线的方法.该曲线应通过半径参数定义.
I have tried a lot of different approaches from examples around the web, but I can't seem to get this to work. I am trying to make a method that draws a curved line between 2 points on a canvas. The curve should be defined by a radius parameter.
下面是我当前的代码.
Below is my current code.
public OverlayBuilder drawCurvedArrow(int startX, int startY, int endX, int endY, int curveRadius, int padding, int color) {
PointF mPoint1 = new PointF(startX, startY);
PointF mPoint2 = new PointF(endX, endY);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(12);
paint.setColor(color);
Path myPath = new Path();
myPath.moveTo(startX, startY);
myPath.quadTo(mPoint1.x, mPoint1.y, mPoint2.x, mPoint2.y);
canvas.drawPath(myPath, paint);
return this;
}
编辑
问题是我不知道如何弯曲在画布上绘制的线.
Edit
The problem is that I can't figure out how to curve the line that is drawn on the canvas.
推荐答案
我自己找到了解决问题的方法.即使有一些很好的答案,也不能完全解决我的特定问题.
I found a solution to my problem myself. Even though there were some great answers, they weren't an exact solution to my particular problem.
这是我所做的:
- 在两个给定点之间找到一个点
- 计算两点之间的90度角
- 使用之前计算出的度数,计算出从中点开始的点X像素.
- 在这3个点上使用"path.cubicTo"(同时使用负值和正值来确定直线弯曲的方式).
如果其他人也应该遇到相同的问题,这是我的代码:
Here is my code if anyone else should run into the same problem:
public OverlayBuilder drawCurvedArrow(int x1, int y1, int x2, int y2, int curveRadius, int color, int lineWidth) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(lineWidth);
paint.setColor(ContextCompat.getColor(context, color));
final Path path = new Path();
int midX = x1 + ((x2 - x1) / 2);
int midY = y1 + ((y2 - y1) / 2);
float xDiff = midX - x1;
float yDiff = midY - y1;
double angle = (Math.atan2(yDiff, xDiff) * (180 / Math.PI)) - 90;
double angleRadians = Math.toRadians(angle);
float pointX = (float) (midX + curveRadius * Math.cos(angleRadians));
float pointY = (float) (midY + curveRadius * Math.sin(angleRadians));
path.moveTo(x1, y1);
path.cubicTo(x1,y1,pointX, pointY, x2, y2);
canvas.drawPath(path, paint);
return this;
}
这是实现示例的示例:
这篇关于如何在画布上的两个点之间绘制一条曲线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!