wotan2009
wotan2009

Reputation: 193

Drawing curve from several points

I would like to know how to join point together to form a curve. I have 20 points in a diagram and would like to know how to join to them. I tried with GeneralPath object, but would like to know if there is a better way?

Upvotes: 2

Views: 3276

Answers (5)

Sergey Aslanov
Sergey Aslanov

Reputation: 2415

To build a curve, and not just lines, you can use method of GeneralPath

public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3)

which creates Bezier curve. But to calculate control points x1, y1, x2, y2 you need to put some maths, or download some interpolation library.

Also you can check this question, it has a links to source code implementing some interpolation algorithms.

Upvotes: 1

Chris Dennett
Chris Dennett

Reputation: 22741

It sounds like you need a Catmull-Rom curve instead. See http://www.mvps.org/directx/articles/catmull/ for more details, and http://johnsogg.blogspot.com/2010/01/cardinal-splines-and-catmull-rom.html for an implementation.

Upvotes: 3

SteeveDroz
SteeveDroz

Reputation: 6156

Bézier imagined a curve based on the polynomial element:

(a + b)^3 = a^3 + 3a^2*b + 3a*b^2 + b^3

(^ being "to the power" and not "XOR"). He actually replaced a by t and b by 1-t. So that the formula would be (t + (1 - t))^3 (Yes, it's equal to 1).

At this point, we have the formula

t^3 + 3*t^2*(1-t) + 3*t*(1-t)^2 + (1-t)^3

There are 4 parts. Choose 4 points.

(x1,y1), (x2,y2), (x3,y3), (x4,y4)

Now, create parametric equations, multiplying every part of the formula by a coordinate, like this:

x(t) = t^3*x1 + 3*t^2*(1-t)*x2 + 3*t*(1-t)^2*x3 + (1-t)^3*x4
y(t) = t^3*y1 + 3*t^2*(1-t)*y2 + 3*t*(1-t)^2*y3 + (1-t)^3*y4

This is the parametric equation of the cubic Bézier.

You want a 20th power Bézier? "simply" develop (t + (1-t))^20.

Pascal Triangle should help you.

Upvotes: 2

jzd
jzd

Reputation: 23639

GeneralPath is a fine approach and should handle your requirement just fine unless you are leaving something else out. Path2D is a new class that can be more precise but if you don't need that precision there is no advantage to it over GeneralPath.

Upvotes: 2

Sam Barnum
Sam Barnum

Reputation: 10744

GeneralPath is certainly the most straightforward. Create your path, call moveTo for your first point, then call lineTo for each subsequent point. Then draw it to a Graphics2D object.

Upvotes: 3

Related Questions