Skip to content

Instantly share code, notes, and snippets.

@tungd
Created November 30, 2011 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tungd/1409759 to your computer and use it in GitHub Desktop.
Save tungd/1409759 to your computer and use it in GitHub Desktop.
Antialias function plotting test
package com.tungd;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Line2D;
import java.awt.geom.QuadCurve2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* @author tung
*/
public class Grapher {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
JFrame mainFrame = new JFrame("ax^2 + bx + c");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GraphCanvas canvas = new GraphCanvas();
mainFrame.add(canvas);
mainFrame.setSize(600, 400);
mainFrame.setVisible(true);
}
}
class GraphCanvas extends JPanel {
public static double A = 0.02;
public static double B = 0;
public static double C = 0;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.WHITE);
int w = getWidth();
int h = getHeight();
// Kind of addicted to HTML5 canvas.getContext()
Graphics2D ctx = (Graphics2D) g;
// Getting to the standard coordinates
ctx.translate(w / 2, h / 2);
ctx.rotate(Math.PI);
// AA: F Why This Not On By Default
ctx.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON));
// Draw our graph using line segments
ctx.setColor(Color.RED);
ctx.setStroke(new BasicStroke(2f));
int pX = -w / 2;
double pY = y(pX);
for (int x = -w / 2; x < w / 2; x += 1) {
ctx.draw(new Line2D.Double(pX, pY, x, y(x)));
pX = x;
pY = y(x);
}
// Draw our graph using QuadraticCurve
ctx.setColor(Color.BLUE);
ctx.draw(new QuadCurve2D.Double((double) w / 4, (double) h / 2,
(double) 0, (double) -h/2,
(double) -w/4, (double) h/2));
}
public double y(int x) {
return A * x * x + B * x + C;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment