Created
October 18, 2021 21:33
-
-
Save marcos-bah/b02c5a92655944c9634ba0b53e54906f to your computer and use it in GitHub Desktop.
Desenhando poligonos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.Graphics; | |
import javax.swing.*; | |
import java.awt.*; | |
import java.awt.geom.GeneralPath; | |
public class JPoligonosRegulares extends JPanel { | |
// parametros: numero de lados, tamanho e cores. | |
private int numLados; | |
private int tamanho; | |
private Color[] cores; | |
// construtor | |
public JPoligonosRegulares(int numLados, int tamanho, Color[] cores) { | |
this.numLados = numLados; | |
this.tamanho = tamanho; | |
this.cores = cores; | |
} | |
public GeneralPath draw() { | |
GeneralPath poligono = new GeneralPath(); // cast g to Graphics2D | |
// calcula o angulo de cada lado | |
double angulo = 2 * Math.PI / numLados; | |
// calcula o raio | |
double raio = tamanho / 2; | |
// calcula o centro do desenho | |
int x = getWidth() / 2; | |
int y = getHeight() / 2; | |
// desenha o primeiro ponto | |
int x0 = (int) (x + raio * Math.cos(0)); | |
int y0 = (int) (y + raio * Math.sin(0)); | |
poligono.moveTo(x0, y0); | |
// desenha os demais pontos | |
for (int i = 0; i < numLados; i++) { | |
poligono.lineTo(x + (int) (raio * Math.cos(angulo * i)), y + (int) (raio * Math.sin(angulo * i))); | |
} | |
// fecha o poligono | |
poligono.closePath(); | |
return poligono; | |
} | |
public void fill(GeneralPath poligono, Graphics2D g) { | |
int x0 = poligono.getBounds().x; | |
int y0 = poligono.getBounds().y; | |
int xf = poligono.getBounds().x + poligono.getBounds().width; | |
int yf = poligono.getBounds().y + poligono.getBounds().height; | |
// gradiente de cores | |
GradientPaint gradiente = new GradientPaint(x0, y0, cores[0], xf, yf, cores[1]); | |
g.setPaint(gradiente); | |
g.fill(poligono); | |
} | |
public void paintComponent(Graphics g) { | |
super.paintComponent(g); | |
fill(draw(), (Graphics2D) g); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment