2015-02-11 35 views
1

我正在試圖製作一個類似形狀的四軸飛行器,所以我必須圍繞不同點旋轉不同的形狀。如何使用Graphics2D在兩個不同點上旋轉兩個形狀?

下面的代碼片段適用於第一個矩形,而不是第二個矩形。

public void render(Graphics2D g) { 
    // cx and cy is the center of the shape these spin near 

    // add prop rotation 
    at = g.getTransform(); 
    at.rotate(Math.toRadians(prop_rotation), cx, cy-42); 
    g.setTransform(at); 

    // Rect 1 spins correctly! 
    g.fillRect(cx-14, cy-45, 28, 6); 

    at = g.getTransform(); 
    at.rotate(Math.toRadians(prop_rotation), cx, cy+38); 
    g.setTransform(at); 
    // Rect 2 spins around rect 1 
    g.fillRect(cx-14, cy+35, 28, 6); 
} 

Picture

那麼,如何做到這一點與多中心?

回答

1

轉換是積累的。

開始通過抓住Graphics上下文的副本,並在隔離修改它...

Graphics2D copy = (Graphics2D)g.create(); 
at = copy.getTransform(); 
at.rotate(Math.toRadians(prop_rotation), cx, cy-42); 
copy.setTransform(at); 

// Rect 1 spins correctly! 
copy.fillRect(cx-14, cy-45, 28, 6); 
copy.dispose(); 

Graphics2D copy = (Graphics2D)g.create(); 
at = copy.getTransform(); 
at.rotate(Math.toRadians(prop_rotation), cx, cy+38); 
copy.setTransform(at); 
// Rect 2 spins around rect 1 
copy.fillRect(cx-14, cy+35, 28, 6); 
copy.dispose(); 

這基本上使Graphics屬性的副本,但仍允許您要繪製的相同的「面」 。更改副本屬性不會影響原件。

另一種可能是改變本身的形狀......

private Rectangle housing1; 
//... 
housing1 = new Rectangle(28, 6); 

//... 

AffineTransform at = new AffineTransform(); 
at.translate(cx - 14, cy - 45); 
at.rotate(Math.toRadians(prop_rotation), cx, cy - 42); 
Shape s1 = at.createTransformedShape(housing1); 
g.fill(housing1); 

這樣,你做的Graphics背景下不亂(這是總是好的),並且獲得一個方便的小件可能例如,對於另一方...

at = new AffineTransform(); 
at.translate(cx-14, cy+35); 
at.rotate(Math.toRadians(prop_rotation), cx, cy + 38); 
Shape s2 = at.createTransformedShape(housing1); 
g.fill(housing2);