Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a curved line between 2 points on canvas?

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.

like image 480
Langkiller Avatar asked May 25 '16 09:05

Langkiller


1 Answers

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.

Here is what I did:

  • Found the point in between the 2 given points
  • Calculated the angle 90 degrees between the 2 points
  • Calculated the point X pixels from the middle point using the calculated degree from before.
  • Used "path.cubicTo" with these 3 points (Takes both negative and positive values to determine which way the line should curve).

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

And here is an example of how the implementation looks like:

enter image description here

like image 126
Langkiller Avatar answered Oct 14 '22 08:10

Langkiller