在晦涩的位置绘制的形状

时间:2017-02-24 14:14:16

标签: java graphics shape

这是一个非常奇怪的错误,我似乎无法弄明白。为了简化这一点,我有三个类:一个Canvas类(用Graphics2D.draw()绘制对象)然后是很多ob家具类,可以看作是一个类,因为它们只是返回不同的形状。最后我有一个CustomShape类,它允许我根据我现有的其他形状创建一个新的Shape。但形状正在奇怪的地方绘制。 x任何y坐标与绘制形状的位置不匹配。

Closet.java:

public class Closet {
    double x, y, width, height, rotation;
    Color color;
Closet() {
    this.x = X;
    this.y = Y;
    this.width = 40;
    this.height = 40;
    this.rotation = 0;
    this.color = Color.blue;
}

public Shape getShape() {
    GeneralPath closetShape = new GeneralPath();
    closetShape.append(new Rectangle2D.Double(0, 0, width, height), false);
    closetShape.moveTo(0 , 0);
    closetShape.lineTo(width, height);
    closetShape.moveTo(0, height);
    closetShape.lineTo(width, 0);
    // transform:

    AffineTransform t = new AffineTransform();
    t.translate(x, y);
    Rectangle2D umriss = closetShape.getBounds2D();
    t.rotate(Math.toRadians(rotation),umriss.getX()+umriss.getWidth()/2,umriss.getY()+umriss.getHeight()/2);
      return  t.createTransformedShape(closetShape);
}
}

CustomShape.java

public class CustomShape  {
double x, y, width, height, rotation;
Color color;
private Closet[] c;
CustomShape(Closet... elements) {
    this.m = elements;
    GeneralPath path = new GeneralPath();
    Closet[] newC = elements.clone();
    Arrays.stream(newC).forEach(e -> path.append(e.getShape(), false));
    this.x = path.getBounds2D().getX();
    this.y = path.getBounds2D().getY();
    this.width = path.getBounds2D().getWidth();
    this.height = path.getBounds2D().getHeight();
    this.rotation = 0;
    this.color = Color.blue;
}

public Shape getShape() {
    GeneralPath path = new GeneralPath();
    Arrays.stream(c).forEach(e -> path.append(e.getShape(), false));
    AffineTransform t = new AffineTransform();
    t.translate(x, y);
    Rectangle2D umriss = path.getBounds2D();
    t.rotate(Math.toRadians(rotation),umriss.getX()+umriss.getWidth()/2,umriss.getY()+umriss.getHeight()/2);
    return t.createTransformedShape(path);
}
}

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:我在将这些Shapes添加到CustomShape之前对其进行了转换。这就是x和y坐标错误的原因。