Friday, December 10, 2010

Draw Parametric Curve Using Java

Guys, have you known about Parametric Curve? I do not really know about its definition exactly. But you may need to read here to get more information. Actually, I heard it from Computer Graphic course in my college. I like this course, especially this chapter (about Parametric Curve). Why? You'll know it soon. :)

Now, we'll draw a Parametric Curve to computer screen using Java programming language. Ok, here we go:

Just for information, I use Netbeans IDE to code these source. Here the first Parametric Curve.


Nice! I created that from this formula:

x(t) = (r1 + r2) * cos (t * 2) – p * cos ((r1 + r2) * t / r2)
y(t) = (r1 + r2) * sin (t * 2) – p * sin ((r1 + r2) * t / r2)


If you want to draw using java, it would be more complicated of course. :)

package parametriccurve;

/**
 *
 * @author ilham
 * @homepage http://hamzcraze.blogspot.com
 *
 */

import java.awt.*;
import javax.swing.*;

public class ParametricCurve1 extends JApplet {

    public static void main(String s[]) {
        JFrame frame = new JFrame();
        // Get the size of the screen

        frame.setTitle("curve 1");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int height = screenSize.height;
        int width = screenSize.width;
        frame.setSize(width / 2, height / 2);

        frame.setLocationRelativeTo(null);

        frame.setResizable(false);
        JApplet applet = new ParametricCurve1();
        applet.init();
        frame.getContentPane().add(applet);
        frame.pack();
        frame.setVisible(true);
    }

    public void init() {
        JPanel panel = new SpiroPanel();
        getContentPane().add(panel);
    }
}

class SpiroPanel extends JPanel {

    int nPoints = 1000;
    double r1 = 95;
    double r2 = 35;
    double p = 185;

    public SpiroPanel() {
        setPreferredSize(new Dimension(400, 400));
        setBackground(Color.white);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.translate(200, 200);
        g2.setColor(Color.red);
        int x1 = (int) (r1 + r2 - p);
        int y1 = 0;
        int x2;
        int y2;


        for (int i = 0; i < nPoints; i++) {
            double t = i * Math.PI / 90;

            x2 = (int)((r1+r2)*Math.cos(t*2)-p*Math.cos((r1+r2)*t/r2));
            y2 = (int)((r1+r2)*Math.sin(t*2)-p*Math.sin((r1+r2)*t/r2));

            g2.drawLine(x1, y1, x2, y2);
            x1 = x2;
            y1 = y2;
        }
    }
}


I have tried some other formulas. Here the results.



Whoaa! It's nice right? Change the formula, and you'll get another nice graphic. :) Well, if you wanna download the complete source code, just take it here: download source code parametric curve using Java.

Enjoy! :D

2 comment(s):

Post a Comment

feel free to write your comment here.. :)