2017-02-24 83 views
1

這是一個非常奇怪的錯誤,我似乎無法弄清楚。爲了簡化這一點,我有三個類:一個Canvas類(它用Graphics2D.draw()繪製對象),然後是許多ob傢俱類,可以將其視爲一個類,因爲他們所做的只是返回不同的形狀。最後,我有一個CustomShape類,它可以讓我根據現有的其他形狀創建一個新的Shape。但形狀正在怪異的地方畫出來。任何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); 
} 
} 
+0

改變你的Graphics2D平移/旋轉而不是做你的形狀內的平移和旋轉不是更好嗎?這樣的形狀可以保持不變,你不需要每次創建一個新的形狀。 – john16384

回答

1

我找到了解決辦法:我將它們添加到CUSTOMSHAPE之前就改變這些形狀。這就是爲什麼x和y座標是錯誤的。