Drawing Cubic Curves

• Print
Java expert Geoff Friesen shows how to use Java 2D's CubicCurve2D class to draw cubic curves. These curves are useful in a variety of applications, including automotive design software.
From the author of

From the author of 

The CubicCurve2D class (located in the java.awt.geom package) is used to create cubic curves. Each cubic curve is constructed from a start point, an endpoint, and two control points (points that determine the shape of the curve). The following code fragment creates a cubic curve:

```CubicCuve2D cubic = new CubicCurve2D.Double (0.0, 50.0, 50.0, 25.0,
75.0, 75.0, 100.0, 50.0);```

The start point is located at (0.0, 50.0) and the endpoint is located at (100.0, 50.0). The first control point is located at (50.0, 25.0) and the second control point is located at (75.0, 75.0). Listing 1 presents source code to a ShapeDemo2 applet that demonstrates drawing a cubic curve.

Listing 1  The ShapeDemo2 applet source code

```// ShapeDemo2.java

import java.awt.*;
import java.awt.geom.*;

public class ShapeDemo2 extends java.applet.Applet
{
public void paint (Graphics g)
{
int w = getSize ().width;
int h = getSize ().height;

CubicCurve2D cubic = new CubicCurve2D.Double (w / 2 - 50,
h / 2,
w / 2 - 25,
h / 2 - 25,
w / 2 + 25,
h / 2 + 25,
w / 2 + 50,
h / 2);

// Draw first control point.

g.drawLine (w / 2 - 25, h / 2 - 25, w / 2 - 25, h / 2 - 25);

// Draw second control point.

g.drawLine (w / 2 + 25, h / 2 + 25, w / 2 + 25, h / 2 + 25);

// Draw the curve.

Graphics2D g2 = (Graphics2D) g;

g2.draw (cubic);
}
}```

ShapeDemo2 draws the two control points in addition to the curve. Figure 1 shows the result.

Figure 1

A cubic curve's appearance is governed by a pair of control points.

If you're looking for an interactive program that allows you to move the start points, endpoints, and control points of a cubic curve, check out the 2D graphics trail in the Java tutorial.

Version 1.3 of the Java 2 SDK introduces two new CubicCurve2D methods for solving cubic equations—equations of the form dx^3 + ax^2 + bx + c = 0. The solveCubic (double [] eqn) and solveCubic (double [] eqn, double [] res) methods take an eqn array of four equation coefficients: eqn [0] contains c, eqn [1] contains b, eqn [2] contains a, and eqn [3] contains d. A return value of -1 identifies a constant equation (b, a, and d are 0). Otherwise, this value represents the number of noncomplex roots (values of x that make the equation evaluate to 0). If a second res array is passed, roots are stored in this array. Otherwise, they're stored in eqn.