gpt4 book ai didi

java - 将 Shape 转换为 Rectangle2D.Double 的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-01 22:48:45 24 4
gpt4 key购买 nike

我需要变换(旋转)一个Rectangle2D.Double 。但是,我不仅需要绘制形状,还需要将转换后的矩形保留为对象,以便我可以使用 .intersects()和其他方法。这是我目前正在改造的方式

private Rectangle2D.Double transform(Rectangle2D.Double rect) {

// make a new transform
AffineTransform transform = new AffineTransform();
// apply the transformation
transform.rotate(Math.toRadians(theta), rect.x + rect.width / 2, rect.y + rect.height / 2);
// get the resulting Shape
Shape s = transform.createTransformedShape(hitbox);
//return the finalized Rectangle
// ?
}

现在,人们会认为以下内容可行

Rectangle2D.Double newRect = new Rectangle2D.Double();
newRect.setFrame(transform.createTransformedShape(rect).getBounds2D());

但是,绘制时,这似乎根本不旋转矩形,而是将其缩放非常大的量(140 倍)。

所以问题是:我怎样才能得到Shape ,顺便说一句,绘制时似乎已正确转换为正确的形式,即 Rectangle2D.Double

如果不可能,那么还有什么好的替代方案仍然具有 .intersects()和类似的方法?

最佳答案

Rectangle2D 是轴对齐的。它无法转动。尝试使用 Path2D 代替。有一个很好的构造函数,它似乎完全符合您的要求:
Path2D.Double(Shape shape, AffineTransform transform)

private Path2D.Double transform(Rectangle2D.Double rect) {

AffineTransform transform = new AffineTransform();
double angle = Math.toRadians(theta);
transform.rotate(angle, rect.x + rect.width / 2, rect.y + rect.height / 2);

return new Path2D.Double(rect, transform);
}

另请注意,您的 toRadians(toRadians(theta)) 非常可疑,并使您的角度非常小。

关于java - 将 Shape 转换为 Rectangle2D.Double 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24986287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com