Java 使用Graphics2D刻画雷达蛛网图并生成为图片,包含pom文件以及成功示例图
时间: 2024-03-19 07:43:10 浏览: 78
好的,以下是一个可以绘制雷达蛛网图并生成为图片的 Java 示例代码:
```java
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.BasicStroke;
import java.awt.Font;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
public class RadarChart {
private int width;
private int height;
private double[] values;
private String[] labels;
private int sides;
public RadarChart(int width, int height, double[] values, String[] labels, int sides) {
this.width = width;
this.height = height;
this.values = values;
this.labels = labels;
this.sides = sides;
}
public void draw(String fileName) {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setBackground(Color.WHITE);
g2d.clearRect(0, 0, width, height);
int cx = width / 2;
int cy = height / 2;
int r = Math.min(cx, cy) - 50;
g2d.setStroke(new BasicStroke(2f));
g2d.setColor(Color.BLACK);
// 绘制雷达蛛网图
for (int i = 1; i <= sides; i++) {
int x = cx + (int) (r * Math.sin(i * 2 * Math.PI / sides));
int y = cy + (int) (r * Math.cos(i * 2 * Math.PI / sides));
g2d.drawLine(cx, cy, x, y);
}
g2d.setStroke(new BasicStroke(1f));
// 绘制数据节点和连线
g2d.setColor(Color.BLUE);
for (int i = 0; i < sides; i++) {
double value = values[i];
int x1 = cx + (int) (r * Math.sin(i * 2 * Math.PI / sides));
int y1 = cy + (int) (r * Math.cos(i * 2 * Math.PI / sides));
int x2 = cx + (int) (r * value * Math.sin(i * 2 * Math.PI / sides));
int y2 = cy + (int) (r * value * Math.cos(i * 2 * Math.PI / sides));
g2d.drawLine(x1, y1, x2, y2);
g2d.fillOval(x2 - 3, y2 - 3, 6, 6);
}
// 绘制标签
g2d.setColor(Color.BLACK);
Font font = new Font("Arial", Font.BOLD, 14);
g2d.setFont(font);
for (int i = 0; i < sides; i++) {
String label = labels[i];
int x = cx + (int) ((r + 20) * Math.sin(i * 2 * Math.PI / sides));
int y = cy + (int) ((r + 20) * Math.cos(i * 2 * Math.PI / sides));
int w = g2d.getFontMetrics().stringWidth(label);
int h = g2d.getFontMetrics().getHeight();
g2d.drawString(label, x - w / 2, y + h / 2);
}
try {
// 将绘制的雷达蛛网图导出为图片
ImageIO.write(image, "png", new File(fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
double[] values = {0.6, 0.8, 0.7, 0.9, 0.5, 0.3};
String[] labels = {"A", "B", "C", "D", "E", "F"};
RadarChart chart = new RadarChart(500, 500, values, labels, 6);
chart.draw("radar.png");
}
}
```
在上面的示例代码中,我们使用 Graphics2D 类来绘制雷达蛛网图,然后使用 ImageIO 类将绘制的图形导出为 PNG 图片。还需要在项目的 pom.xml 文件中添加以下依赖项:
```xml
<dependencies>
<dependency>
<groupId>com.sun.media</groupId>
<artifactId>jai-codec</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.apache.xmlgraphics</groupId>
<artifactId>batik-svggen</artifactId>
<version>1.14</version>
</dependency>
</dependencies>
```
希望这个示例可以帮助你!
阅读全文