Friday, 25 May 2012

Draw Lines giving parabolic effect in Java

Today I am going to post a program in Java that will create an art using Java 2DGraphics and geometry. This code creates a curve like a parabola as shown in the screenshot below.
Here a set of lines are drawn with different points. The lines are drawn by joining of two points. These points are calculated very precisely over here so that whole thing gives a parabola like curve.It is very simple to create this design. Here is the code for you.

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

public class Art extends Component {

     public static void main(String[] args) {
         try {
         ApplicationFrame f = new ApplicationFrame("ShowOff v1.0");
         f.setLayout(new BorderLayout());
         Art obj = new Art();
         f.add(obj, BorderLayout.CENTER);
      }catch (Exception e) {
   private int mNumberOfLines = 25;
   private Color[] mColors = {,, }; 

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        Dimension d = getSize();
        for (int i = 0; i < mNumberOfLines; i++) {
           double ratio = (double)i / (double)mNumberOfLines;
           double ratio2 = (double)(mNumberOfLines-i-1) / (double)mNumberOfLines;
           Line2D line1 = new Line2D.Double(0, ratio * d.height,
                ratio * d.width, d.height);
           Line2D line2 = new Line2D.Double(ratio*d.width,0,
                d.width, ratio*d.height);
           Line2D line3 = new Line2D.Double(d.width,ratio*d.height,
                ratio2*d.width, d.height);
           Line2D line4 = new Line2D.Double(ratio2*d.width,0,
                0, ratio*d.height);
           g2.setPaint(mColors[i % mColors.length]);

Note : This program won't compile unless you create a Java source file named ApplicationFrame that works as a Frame object by inheriting it. So please make the necessary changes. The actual Graphics code which has given the output as shown is written in the paint(Graphics) method.

Hope this helps.

1 comment: