Java 可视化绘制形状:输入坐标字符串,支持直线和圆弧
以下是使用Java编写的程序,根据输入的字符串画出可视化形状:
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class ShapeVisualization extends JFrame {
private String input;
public ShapeVisualization(String input) {
this.input = input;
setTitle('Shape Visualization');
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
String[] points = input.split(';');
int numPoints = points.length;
double[] xPoints = new double[numPoints];
double[] yPoints = new double[numPoints];
boolean[] isArc = new boolean[numPoints];
for (int i = 0; i < numPoints; i++) {
String point = points[i];
if (point.startsWith('(')) {
point = point.substring(1, point.length() - 1);
isArc[i] = true;
} else {
isArc[i] = false;
}
String[] coordinates = point.split(',');
xPoints[i] = Double.parseDouble(coordinates[0]);
yPoints[i] = Double.parseDouble(coordinates[1]);
}
GeneralPath path = new GeneralPath();
path.moveTo(xPoints[0], yPoints[0]);
for (int i = 1; i < numPoints; i++) {
if (isArc[i]) {
double x1 = xPoints[i];
double y1 = yPoints[i];
double x2 = xPoints[i + 1];
double y2 = yPoints[i + 2];
double cx = xPoints[i + 2];
double cy = yPoints[i + 3];
boolean clockwise = Boolean.parseBoolean(points[i + 3]);
Arc2D arc = new Arc2D.Double();
arc.setArcByCenter(cx, cy, Point2D.distance(cx, cy, x1, y1), 0, 0, 0);
arc.setAngles(x1, y1, x2, y2);
if (clockwise) {
arc.setAngleExtent(arc.getAngleExtent() - 360);
}
path.append(arc, true);
i += 3;
} else {
path.lineTo(xPoints[i], yPoints[i]);
}
}
path.closePath();
g2d.draw(path);
}
public static void main(String[] args) {
String input = '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);';
ShapeVisualization shapeVisualization = new ShapeVisualization(input);
shapeVisualization.setVisible(true);
}
}
可以直接运行上述代码,程序会创建一个窗口并绘制出输入字符串对应的形状。
原文地址: https://www.cveoy.top/t/topic/o1zC 著作权归作者所有。请勿转载和采集!