/* BezierCurve.java * * Draw a Bezier curve using the parametric form. * * Bruce M. Bolden * April 30, 2001 * http://www.cs.uidaho.edu/~bruceb/cs127/code/Bezier/ */ import java.awt.*; public class BezierCurve { static final int INSET = 80; static final int MIN_DIVISIONS = 10; static final int POINT_SIZE = 3; Point b[] = new Point[4]; // Vertices of the control polygon int nDivs = 25; // divisions of the Bezier curve int windowSize; // display region size Color background; BezierCurve( Color bgC, int h, int w ) { background = bgC; windowSize = Math.min( h, w ); // minimum of height and width b[0] = new Point( INSET, windowSize-INSET ); b[1] = new Point( INSET, INSET ); b[2] = new Point( windowSize-INSET, INSET ); b[3] = new Point( windowSize-INSET, windowSize-INSET ); } void setDivisions( int n ) { // Negative or less than 10 is useless nDivs = Math.max( n, MIN_DIVISIONS ); } /** Draw Bezier curve using "nDivs" divisions. */ public void drawBezierCurve( Graphics g ) { g.setColor( background ); g.fillRect( 0, 0, windowSize, windowSize ); // Check points/Show control polygon g.setColor( Color.yellow ); g.drawLine( b[0].x, b[0].y, b[1].x, b[1].y ); g.drawLine( b[1].x, b[1].y, b[2].x, b[2].y ); g.drawLine( b[2].x, b[2].y, b[3].x, b[3].y ); g.setColor(Color.gray); g.drawLine( b[3].x, b[3].y, b[0].x, b[0].y ); for( int i = 0 ; i < b.length ; i++ ) { g.fillOval( b[i].x, b[i].y, 2*POINT_SIZE, 2*POINT_SIZE ); //System.out.print( "b[" + i + "]: " ); //System.out.println( b[i].x + ", " + b[i].y ); } // Display points on curve g.setColor(Color.red); // point color Point p = new Point(); double t; // parametric value double onemt; // (1-t) double onemt2; // (1-t)^2 double j30, j31, j32, j33; // Bernstein coefficients for( t = 0.0 ; t <= 1.0 ; t += 1.0/(double)nDivs ) { onemt = 1.0 - t; onemt2 = onemt * onemt; j30 = onemt * onemt2; // (1-t)^3 j31 = 3.0*t * onemt2; j32 = 3.0*t*t * onemt; j33 = t * t * t; p.x = (int)(j30*b[0].x + j31*b[1].x + j32*b[2].x + j33*b[3].x); p.y = (int)(j30*b[0].y + j31*b[1].y + j32*b[2].y + j33*b[3].y); //System.out.println( "p[" + t + "]: " + p.x + ", " + p.y ); g.fillOval( p.x, p.y, POINT_SIZE, POINT_SIZE ); } } }