import java.awt.*; import java.applet.Applet; import java.awt.image.BufferedImage; public class MandelbrotFractal extends Applet { private int height = 500; private int width = 500; private Color [][] picture; private BufferedImage image; private Generator gen; public void init() { gen = new Generator(); gen.render(); image = matrixToImage(picture); } public void paint(Graphics g) { g.drawImage(image, 0, 0, this); } private BufferedImage matrixToImage(Color[][] matrix) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int i = 0; i < height; ++i) for (int k = 0; k < width; ++k) image.setRGB(k, i, matrix[i][k].getRGB()); return image; } private class Generator { private Complex[][] complex; private Color[] colors; public Generator() { generateColors(); } public Color[][] render() { mesh(); picture = new Color[height][width]; int pixelSize = 1; int nextIm = pixelSize/2; for(int i = 0; i < height; i++) { int nextRe = pixelSize/2; for(int j = 0; j < width; j++) { Complex c = new Complex(0, 0); int iterations=0; while(c.getAbs2() < 4 && iterations<199) { c.mul(c); c.add(complex[nextIm][nextRe]); iterations++; } if(iterations == 199) picture[0][j] = Color.BLACK; else picture[0][j] = colors[iterations]; nextRe += pixelSize; } nextIm += pixelSize; } return picture; } private void mesh() { complex = new Complex[height][width]; double minRe = -2.4; double maxRe = 0.8; double minIm = -1.4; double maxIm = 1.4; double dRe = (maxRe - minRe) / width; double dIm = (maxIm - minIm) / height; for(int i = 0; i < height; i++) for(int j = 0; j < width; j++) complex[i][j] = new Complex(minRe + j*dRe, maxIm - i*dIm); } private void generateColors() { colors = new Color[200]; int red = 255; int green = 255; int blue = 255; for(int k = 0; k < 40; k++){ // -> röd colors[k] = new Color(red,green,blue); blue -= 5; green -= 5; } for(int k = 0; k < 40; k++){ // -> gul colors[40+k] = new Color(red,green,blue); green += 5; } for(int k = 0; k < 40; k++){ // -> vit colors[80+k] = new Color(red,green,blue); blue += 5; } for(int k = 0; k < 40; k++){ // -> turkos colors[120+k] = new Color(red,green,blue); red -= 5; } for(int k = 0; k < 40; k++){ // -> blå colors[160+k] = new Color(red,green,blue); green -= 5; } } } class Complex { private double re, im; public Complex(double re, double im) { this.re = re; this.im = im; } public double getRe() { return re; } public double getIm() { return im; } public double getAbs2() { return re*re + im*im; } public void add(Complex c) { re += c.getRe(); im += c.getIm(); } public void mul(Complex c) { double r1 = re; double i1 = im; double r2 = c.getRe(); double i2 = c.getIm(); re = r1*r2 - i1*i2; im = r1*i2 + i1*r2; } } }