ava使用Graphics2D刻画六边形菱形蛛网图,样式类似游戏人物能力图
时间: 2024-03-19 21:43:54 浏览: 63
好的,以下是Java使用Graphics2D刻画六边形菱形蛛网图,并且样式类似游戏人物能力图的示例代码:
```java
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
public class SpiderWeb {
private static final int WIDTH = 800; // 图片宽度
private static final int HEIGHT = 800; // 图片高度
private static final int CENTER_X = WIDTH / 2; // 图片中心点横坐标
private static final int CENTER_Y = HEIGHT / 2; // 图片中心点纵坐标
private static final int RADIUS = 300; // 六边形外接圆半径
private static final int EDGE_NUM = 6; // 六边形边数
private static final int LINE_COLOR = 0x000000; // 蛛网线颜色
private static final int LABEL_COLOR = 0x000000; // 标签颜色
private static final Font LABEL_FONT = new Font("微软雅黑", Font.PLAIN, 16); // 标签字体
private static final String[] LABELS = { "攻击力", "物理防御", "魔法防御", "生命值", "法力值", "速度" }; // 标签文字
public static void main(String[] args) {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) image.getGraphics();
g2d.setBackground(Color.WHITE);
g2d.clearRect(0, 0, WIDTH, HEIGHT);
// 绘制六边形
Path2D hexagon = new Path2D.Double();
double angle = Math.PI / 6; // 六边形内角
double x, y;
for (int i = 0; i < EDGE_NUM; i++) {
x = CENTER_X + RADIUS * Math.cos(angle * (2 * i + 1));
y = CENTER_Y + RADIUS * Math.sin(angle * (2 * i + 1));
if (i == 0) {
hexagon.moveTo(x, y);
} else {
hexagon.lineTo(x, y);
}
}
hexagon.closePath();
g2d.setColor(new Color(LINE_COLOR));
g2d.setStroke(new BasicStroke(2));
g2d.draw(hexagon);
// 绘制蛛网线
double step = RADIUS / 5;
for (int i = 1; i <= 5; i++) {
double radius = step * i;
Path2D webLine = new Path2D.Double();
for (int j = 0; j < EDGE_NUM; j++) {
x = CENTER_X + radius * Math.cos(angle * (2 * j + 1));
y = CENTER_Y + radius * Math.sin(angle * (2 * j + 1));
if (j == 0) {
webLine.moveTo(x, y);
} else {
webLine.lineTo(x, y);
}
}
webLine.closePath();
g2d.setColor(new Color(LINE_COLOR));
g2d.setStroke(new BasicStroke(1));
g2d.draw(webLine);
// 绘制标签
g2d.setFont(LABEL_FONT);
for (int j = 0; j < EDGE_NUM; j++) {
double labelX = CENTER_X + radius * Math.cos(angle * (2 * j + 1));
double labelY = CENTER_Y + radius * Math.sin(angle * (2 * j + 1));
g2d.setColor(new Color(LABEL_COLOR));
g2d.drawString(LABELS[j], (float) labelX, (float) labelY);
}
}
// 保存图片
File file = new File("spiderweb.png");
try {
ImageIO.write(image, "png", file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个示例代码在绘制蛛网图的基础上,增加了标签的绘制。通过循环绘制每一层蛛网线时,可以在同一层的六个顶点处绘制对应的标签。通过调整字体、颜色等参数,可以使蛛网图的样式更符合您的需求。
阅读全文