Java中毕达哥拉斯树的graphics2d可视化表示
我想用Java对毕达哥拉斯树进行可视化表示,代码输出一个PNG固定图像
我首先定义了向量类,它从两个向量分量(x,y)开始,可以旋转向量、缩放向量或将向量添加到另一个向量
public class Vector {
public double x;
public double y;
public Vector(double x, double y) {
this.x = x;
this.y = y;
}
public Vector rotated(double alpha) {
double x1 = Math.cos(alpha) * x - Math.sin(alpha) * y;
double y1 = Math.sin(alpha) * x + Math.cos(alpha) * y;
Vector vRotated = new Vector(x1, y1);
return vRotated;
}
public Vector scaled(double s) {
double x1 = x * s;
double y1 = y * s;
Vector vScaled = new Vector(x1, y1);
return vScaled;
}
public Vector added(Vector v) {
double x1 = this.x+v.x;
double y1 = this.y+v.y;
Vector vAdded = new Vector(x1,y1);
return vAdded;
}
}
我还编写了创建初始图像和背景并将其保存到所需路径的方法
public static void createPythagorasTreeImage(int startSize) throws IOException {
// Creation of the image object
int height = 5 * startSize;
int width = 8 * startSize;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// Create a Graphics2D object from the image and set a white background
Graphics2D g = image.createGraphics();
g.setColor(new Color(255, 255, 255));
g.fillRect(0, 0, width, height);
// Initial position and orientation of the first segment
Vector startPos = new Vector(width / 2, startSize);
Vector up = new Vector(0, 1);
// Start the recursion.
drawSegment(g, startPos, up, startSize, height);
// Save the image as PNG
String OS = System.getProperty("os.name").toLowerCase(); // different for win and unix
String filePath = System.getProperty("user.dir") + (OS.indexOf("win") >= 0 ? "\\" : "/") + "pythagorasTree.png";
System.out.println("Writing pythagoras-tree image to: " + filePath);
ImageIO.write(image, "png", new File(filePath));
}
我已经在维基百科上读到了树的工作原理,现在我想实现这个算法。 我需要的帮助是使用Graphics2D实现这两种方法(我不太熟悉):
public static void drawRotatedRect(Graphics2D g, Vector pos, Vector up, int a, int height) {
}
此方法应使用Graphics2D(可能使用g.fillPolygon()?)绘制正方形,在位置pos处,向上矢量通过指示正方形的向上方向指示正方形的旋转,a是正方形的侧面,高度是绘图空间的高度
public static void drawSegment(Graphics2D g, Vector pos, Vector up, int a, int height) {
}
此方法应使用前一种方法绘制第一个正方形,然后计算两个新正方形的位置和旋转并绘制它们,递归重复此操作,直到正方形具有非常小的边长(2px)
这是我对毕达哥拉斯树的理解,我成功地编写了大部分代码,而且这个想法似乎是正确的,只有当我让两个缺少的方法发挥作用时
# 1 楼答案
通过绘制浮点(或双精度)精度的Path2D,可以使用
Graphics2D
上下文。我提出这一点,因为您会注意到使用int精度可能会给您带来奇怪的效果要绘制路径,请执行以下操作:
请注意,您需要手动绘制矩形,因为它们不需要旋转,
Graphics2D
不适合旋转。您可以尝试使用固有的旋转,但您将对上下文进行像素化,并且您不会喜欢它我非常期待你的结果。完成后,你能将最后一张图片粘贴到你的问题中吗:)