Skip to content

Instantly share code, notes, and snippets.

@yogthos
Created June 16, 2010 04:23
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 yogthos/440158 to your computer and use it in GitHub Desktop.
Save yogthos/440158 to your computer and use it in GitHub Desktop.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.ImageObserver;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Mandelbrot extends Canvas implements ImageObserver {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 1200;
public static final int HEIGHT = 1200;
private static int BAILOUT = 256;
private static int MAX_ITERATIONS = 64;
public BufferStrategy strategy;
public Mandelbrot () {
setBounds(0,0,WIDTH,HEIGHT);
setBackground(Color.BLACK);
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
panel.setLayout(null);
panel.add(this);
JFrame frame = new JFrame("Mandelbrot");
frame.add(panel);
frame.setBounds(0,0,WIDTH, HEIGHT);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create a double buffer
createBufferStrategy(2);
strategy = getBufferStrategy();
requestFocus();
}
private int checkBounds(float x, float y) {
float cr = x;
float ci = y;
float zi = 0.0f;
float zr = 0.0f;
int i = 0;
while (true) {
i++;
float temp = zr * zi;
float zr2 = zr * zr;
float zi2 = zi * zi;
zr = zr2 - zi2 + cr;
zi = temp + temp + ci;
if (zi2 + zr2 > BAILOUT)
return i;
if (i > MAX_ITERATIONS)
return 0;
}
}
private void draw() {
float x = -2.1f, y = -1.5f, z = 3.0f;
int i, j;
Graphics g = strategy.getDrawGraphics();
g.clearRect(0, 0, getWidth(), getHeight());
for (i = 0; i < HEIGHT; i++) {
for (j = 0; j < WIDTH; j++) {
int value = checkBounds((x + z*(i/(float)WIDTH)), (y + z*(j/(float)HEIGHT)));
if (value > 0) {
g.setColor(new Color(value*255/MAX_ITERATIONS));
g.drawRect(i, j, 0, 0);
}
}
}
strategy.show();
}
public static void main(String args[]) {
Mandelbrot m = new Mandelbrot();
long startTime = System.currentTimeMillis();
m.draw();
System.out.println((System.currentTimeMillis() - startTime)/1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment