Java 坐标绘制工具:绘制自定义形状,支持圆弧和闭合路径
以下是一个用Java编写的程序,可以按照给定的坐标顺序绘制多个可视化形状:
import java.awt.*;
import java.awt.geom.*;
public class ShapeDrawer {
public static void main(String[] args) {
String[] shapes = {
'0.000,6.000;0.000,0.000;32.639,0.000;32.639,6.069;0.000,10.069;(0.000,10.069;0.000,6.000;103.105,2.328;true);',
'0.000,6.000;0.000,0.000;32.639,0.000;32.639,6.069;0.000,10.069;(0.000,10.069;0.000,6.000;103.105,2.328;true);'
};
for (String shape : shapes) {
drawShape(shape);
}
}
private static void drawShape(String shapeStr) {
String[] coords = shapeStr.split(';');
int numPoints = coords.length;
double[][] points = new double[numPoints][2];
boolean[] isArc = new boolean[numPoints];
for (int i = 0; i < numPoints; i++) {
if (coords[i].startsWith('(')) {
coords[i] = coords[i].substring(1, coords[i].length() - 1);
isArc[i] = true;
}
String[] xy = coords[i].split(',');
points[i][0] = Double.parseDouble(xy[0]);
points[i][1] = Double.parseDouble(xy[1]);
}
Shape shape = createShape(points, isArc);
drawShape(shape);
}
private static Shape createShape(double[][] points, boolean[] isArc) {
GeneralPath path = new GeneralPath();
path.moveTo(points[0][0], points[0][1]);
for (int i = 1; i < points.length; i++) {
if (isArc[i - 1]) {
double[] p1 = points[i - 1];
double[] p2 = points[i];
double[] p3 = points[(i + 1) % points.length];
double centerX = p2[0];
double centerY = p2[1];
double startAngle = Math.atan2(p1[1] - centerY, p1[0] - centerX);
double endAngle = Math.atan2(p3[1] - centerY, p3[0] - centerX);
double radius = Math.sqrt(Math.pow(p2[0] - centerX, 2) + Math.pow(p2[1] - centerY, 2));
boolean clockwise = isArc[i];
path.append(new Arc2D.Double(centerX - radius, centerY - radius, radius * 2, radius * 2, Math.toDegrees(startAngle), Math.toDegrees(endAngle - startAngle), clockwise ? Arc2D.OPEN : Arc2D.OPEN), true);
} else {
path.lineTo(points[i][0], points[i][1]);
}
}
path.closePath();
return path;
}
private static void drawShape(Shape shape) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(2));
g2d.draw(shape);
}
};
frame.add(panel);
}
}
请注意,这个程序使用了Java的图形库java.awt和javax.swing。它将每个形状绘制到一个新的窗口中,每个形状都是由给定的坐标点和圆弧信息创建的java.awt.Shape对象。每个形状都用黑色线条绘制出来,并且最后一个坐标点会与第一个坐标点连接起来。
你可以将你的字符串集合传递给main方法中的shapes数组,然后运行程序来绘制出形状。请确保你的Java环境已经正确地配置和安装。
原文地址: http://www.cveoy.top/t/topic/o2TC 著作权归作者所有。请勿转载和采集!