Skip to content

Instantly share code, notes, and snippets.

@luketn
Last active August 26, 2018 12:36
Show Gist options
  • Save luketn/8794d210d3b2895866d05b4541d618c5 to your computer and use it in GitHub Desktop.
Save luketn/8794d210d3b2895866d05b4541d618c5 to your computer and use it in GitHub Desktop.
Draw a sin and cos wave
package com.mycodefu;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import static com.mycodefu.Main.WaveFunction.Cosine;
import static com.mycodefu.Main.WaveFunction.Sine;
public class Main {
public static void main(String[] args) throws IOException {
int imageWidth = 400;
int imageHeight = 480;
int border = 20;
BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
for (int angle = 0; angle < 360; angle++) {
int x = border + angle;
for (WaveFunction waveFunction : WaveFunction.values()) {
int y = calculateY(waveFunction, angle, border, imageHeight);
int toX = x + 1;
int toY = calculateY(waveFunction, angle + 1, border, imageHeight);
g.setColor(waveFunction.lineColor);
g.drawLine(x, y, toX, toY);
}
}
//Legend
for (int i = 0; i < WaveFunction.values().length; i++) {
WaveFunction waveFunction = WaveFunction.values()[i];
g.setColor(waveFunction.lineColor);
g.drawString(waveFunction.name(), border, border + border * i);
}
File imageFile = new File("sin_cos.png");
ImageIO.write(image, "png", imageFile);
Desktop.getDesktop().open(imageFile);
}
private static int calculateY(WaveFunction waveFunction, int angle, int border, int imageHeight) {
int drawingHeight = imageHeight - (border * 2);
int waveHeight = drawingHeight / 2;
int centerY = imageHeight / 2;
double angleRadians = angle * Math.PI / 180;
double yFactor; //yFactor is a floating point value between -1 and 1
switch (waveFunction) {
case Cosine: {
yFactor = Math.cos(angleRadians);
break;
}
case Sine: {
yFactor = Math.sin(angleRadians);
break;
}
default:
throw new NotImplementedException();
}
return (int) (yFactor * waveHeight) + centerY;
}
enum WaveFunction {
Sine(Color.BLUE),
Cosine(Color.RED);
private Color lineColor;
WaveFunction(Color lineColor) {
this.lineColor = lineColor;
}
}
}
@luketn
Copy link
Author

luketn commented Aug 26, 2018

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment