Java 绘制六边形蛛网战力图,每个角都有标题,动态能力项绘制未一个不规则的形状并设置背景色为淡蓝色,并输出为图片
时间: 2024-04-04 15:33:15 浏览: 106
好的,与绘制六芒星战力图类似,绘制六边形蛛网战力图也可以使用 Graphics2D 类进行绘制。不同的是,绘制六边形需要使用绘制多边形的方法,并且需要根据能力项的值计算出每个角上的坐标。下面是一个示例代码,仅供参考:
```java
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.geom.GeneralPath;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class RadarChart {
public static void main(String[] args) {
int size = 500; // 图片大小
BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 绘制六边形
Polygon hexagon = new Polygon();
double radius = size / 2.5;
for (int i = 0; i < 6; i++) {
double angle = Math.PI / 3.0 * i + Math.PI / 6.0;
int x = (int) (size / 2.0 + radius * Math.cos(angle));
int y = (int) (size / 2.0 + radius * Math.sin(angle));
hexagon.addPoint(x, y);
}
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(2.0f));
g2d.draw(hexagon);
// 绘制边框
double step = radius / 5.0;
for (int i = 1; i <= 5; i++) {
double r = step * i;
Polygon polygon = new Polygon();
for (int j = 0; j < 6; j++) {
double angle = Math.PI / 3.0 * j + Math.PI / 6.0;
int x = (int) (size / 2.0 + r * Math.cos(angle));
int y = (int) (size / 2.0 + r * Math.sin(angle));
polygon.addPoint(x, y);
}
g2d.draw(polygon);
}
// 绘制标题
String[] titles = {"力量", "敏捷", "耐力", "智力", "精神", "魅力"};
double titleRadius = size / 2.2;
for (int i = 0; i < 6; i++) {
double angle = Math.PI / 3.0 * i + Math.PI / 2.0;
int x = (int) (size / 2.0 + titleRadius * Math.cos(angle));
int y = (int) (size / 2.0 + titleRadius * Math.sin(angle));
g2d.drawString(titles[i], x, y);
}
// 绘制动态能力项
GeneralPath path = new GeneralPath();
double pathRadius = size / 2.5;
double[] values = {0.8, 0.5, 0.9, 0.6, 0.7, 0.4}; // 每个能力项的值
for (int i = 0; i < 6; i++) {
double angle = Math.PI / 3.0 * i + Math.PI / 6.0;
double value = values[i];
double r = pathRadius * value;
int x = (int) (size / 2.0 + r * Math.cos(angle));
int y = (int) (size / 2.0 + r * Math.sin(angle));
if (i == 0) {
path.moveTo(x, y);
} else {
path.lineTo(x, y);
}
}
path.closePath();
g2d.setColor(new Color(0, 191, 255)); // 设置背景色为淡蓝色
g2d.fill(path);
// 输出为图片
try {
ImageIO.write(image, "png", new File("radar-chart.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
运行该代码可以生成一个名为 `radar-chart.png` 的图片文件,其中包含了绘制好的六边形蛛网战力图。
阅读全文