Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bezier curve and canvas

How I can draw bezier curve in canvas. I have only start point and end point. I want to draw line from start point to end point. How I can do this?

like image 399
edi233 Avatar asked Apr 03 '12 12:04

edi233


People also ask

How do you draw a curve in canvas?

To draw a Bezier curve with HTML5 canvas, use the bezierCurveTo() method. The method adds the given point to the current path, connected to the previous one by a cubic Bezier curve with the given control points. You can try to run the following code to learn how to draw a Bezier curve on HTML5 Canvas.

What is the use of Bezier curves?

Bézier curves are widely used in computer graphics to model smooth curves. As the curve is completely contained in the convex hull of its control points, the points can be graphically displayed and used to manipulate the curve intuitively.

What is the difference between a cubic Bézier curve and a quadratic Bézier curve?

A cubic Bezier curve has 2 control points, whereas the quadratic Bezier curve only has 1 control point. Cubic Bezier curves - 3 rd degree curves - to fully define such a curve, one will need to specify 4 points: two anchor points (P1 and P2) - the curve starts and, respectively, ends in these points.


2 Answers

You can use Path.quadTo() or Path.cubicTo() for that. Examples can be found in the SDK Examples (FingerPaint). In your case you would simply need to calculate the middle point and pass then your three points to quadTo()..

Some code for you:

  • (x1,y1) and (x3,y3) are your starting and ending points respectively.
  • create the paint object only once (e.g. in your constructor)

    Paint paint = new Paint() {
        {
            setStyle(Paint.Style.STROKE);
            setStrokeCap(Paint.Cap.ROUND);
            setStrokeWidth(3.0f);
            setAntiAlias(true);
        }
    };
    
    final Path path = new Path();
    path.moveTo(x1, y1);
    
    final float x2 = (x3 + x1) / 2;
    final float y2 = (y3 + y1) / 2;
    path.quadTo(x2, y2, x3, y3);
    canvas.drawPath(path, paint);
    
like image 170
Renard Avatar answered Oct 02 '22 07:10

Renard


With Path you can draw cubic and quadratic bezier curves. See cubicTo() and quadTo()

like image 44
aromero Avatar answered Oct 02 '22 07:10

aromero