2013-10-26 73 views
0

我很新的圖形在Java中,我試圖創建一個形狀,剪輯到另一個形狀的底部。下面是我想要達到一個例子:2D剪輯區域的形狀

http://i.stack.imgur.com/g3jKJ.png

凡在形狀底座上的白線是何許圓形邊緣之內; 我這樣做目前的辦法是,像這樣:

g2.setColor(gray); 
Shape shape = getShape(); //round rectangle 
g2.fill(shape); 
Rectangle rect = new Rectangle(shape.getBounds().x, shape.getBounds().y, width, height - 3); 
Area area = new Area(shape); 
area.subtract(new Area(rect)); 
g2.setColor(white); 
g2.fill(area); 

我仍然與剪輯方法進行實驗,但我似乎無法得到它的權利。目前的方法是否正確(性能明智,因爲組件經常重新繪製)還是有更高效的方法?

+1

發佈您的[SSCCE](http://sscce.org/),證明問題。 – camickr

+0

我懷疑更有效的方法是首先對白色和黃色進行加強,而不是進行區域減法,然而對Area進行少量(可能是昂貴的)操作的話,您仍然在使用相同數量的paintcalls。 – arynaq

+1

讓效率更高的唯一方法是將結果緩衝到BufferedImage上,並簡單地繪製,只根據需要更改緩衝區... – MadProgrammer

回答

1

這是當前的方法確定(性能明智的,因爲該組件重畫經常)..

減去形狀是我怎麼會去了解它。對象可以是幾個實例,或者(可能)是根據需要爲transformed的單個實例。

  1. A text demo.,使用縮放&衰落。
  2. 這是one with simple lines(..和點,..它是動畫)。

當然,如果圖像是純添加劑,使用BufferedImage作爲畫布&顯示它在一個JLabel/ImageIcon組合。就像在這兩個例子中一樣。

1

我認爲你關於使用剪輯方法的最初想法是正確的做法。這適用於我:

static void drawShapes(Graphics2D g, int width, int height, 
    Shape clipShape) { 

    g.setPaint(Color.BLACK); 
    g.fillRect(0, 0, width, height); 

    g.clip(clipShape); 

    int centerX = width/2; 
    g.setPaint(new GradientPaint(
     centerX, 0, Color.WHITE, 
     centerX, height, new Color(255, 204, 0))); 

    g.fillRect(0, 0, width, height); 

    g.setPaint(Color.WHITE); 
    int whiteRectHeight = height * 4/5; 
    g.fillRect(0, whiteRectHeight, 
     width, height - whiteRectHeight); 
}