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?
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.
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.
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
.
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.
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.
精彩评论