我正在尝试在 Swing/JPanel 中创建一些代码,该代码采用一些(可变)变量并绘制如下图:
我不知道从哪里开始。这个想法是在六边形上会有一个关键点,每个变量一个,每个点之间会画一条线,然后自定义形状内部的空间会被遮蔽。有什么想法吗?
代码原型
import java.awt.*;
import javax.swing.*;
public class DrawPolygon extends JPanel {
int xOffset = 0;
int yOffset = 0;
int sizeModifer = 50;
int numOfPoints = 8;
int linePosition = 80;
double sizeMultiplier = 1;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Polygon[] polygons = new Polygon[5];
for (int i = 0; i < polygons.length; i++){
polygons[i] = new Polygon();
for (int q = 0; q < numOfPoints; q++) {
polygons[i].addPoint(
xOffset + (int) (linePosition + (sizeModifer*sizeMultiplier)
* Math.cos(q * 2 * Math.PI / numOfPoints)),
yOffset + (int) ((linePosition - 10) + (sizeModifer*sizeMultiplier)
* Math.sin(q * 2 * Math.PI / numOfPoints)));
}//built points
sizeMultiplier = sizeMultiplier - 0.2;
}//build polygon arrays
Polygon innerPolygon = new Polygon();
for (int i = 0; i < numOfPoints; i++) {
int randomRange = 5 + (int) (Math.random() * ((sizeModifer - 5) + 1));
innerPolygon.addPoint(
xOffset + (int) (linePosition + randomRange
* Math.cos(i * 2 * Math.PI / numOfPoints)),
yOffset + (int) ((linePosition - 10) + randomRange
* Math.sin(i * 2 * Math.PI / numOfPoints)));
}
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setStroke(new BasicStroke(1));
for (int i = 0; i < polygons.length; i++){
g2d.setColor(Color.green);
g2d.fill(polygons[i]);
g2d.setColor(Color.black);
g2d.draw(polygons[i]);
}//draw polygons from arrays
double distanceModifier = 1;
for (int i = 0; i < numOfPoints; i++) {
g2d.drawString("test"+(i+1),
xOffset + (int) (linePosition + (sizeModifer*distanceModifier)
* Math.cos(i * 2 * Math.PI / numOfPoints)),
yOffset + (int) ((linePosition - 10) + (sizeModifer*distanceModifier)
* Math.sin(i * 2 * Math.PI / numOfPoints)));
distanceModifier = distanceModifier +.01;
}
g2d.setColor(new Color(255,213,200,90));
g2d.fill(innerPolygon);
g2d.setColor(Color.red);
g2d.draw(innerPolygon);
}
@Override
public Dimension getPreferredSize() {
// TODO calculate size based on geometry
return new Dimension(160, 160);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Show Different Polygons");
frame.add(new DrawPolygon());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}