2013-12-19 18 views
-1

我有一個圖形對象,我想除了某些矩形以外的所有區域着色。對於例如在Java中着色時不包括區域

enter image description here

我要的顏色都區除了這些黑色區域。我可以這樣做嗎?圖像中可以有很多矩形。

+0

你也着色黑色矩形?如果您在繪製完整圖形之後對其進行着色,那麼它可能會按照您的要求工作。 –

+0

不,我想給除黑色區域以外的所有區域着色。 –

+0

-1,@VaibhavAgarwal,你在哪裏給出了你最後發表的關於這個主題的答案(http://stackoverflow.com/q/20671551/131872)。你爲什麼不花時間看看給出的答案,並在人們幫助你時接受答案?這裏給出的答案與上一個問題中給出的答案几乎相同。 – camickr

回答

2

我建議你用White填充所有區域的顏色,然後在上面畫Black矩形,因爲繪製帶孔的圖形更簡單。例如像下一個:

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Rectangle; 
import java.util.ArrayList; 
import java.util.List; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class DrawExample extends JPanel{ 
    List<Rectangle> rctangles = new ArrayList<>(); 

    public static void main(String[] args) { 

     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     DrawExample drawExample = new DrawExample(); 
     drawExample.addRect(new Rectangle(20,20,25,25)); 
     drawExample.addRect(new Rectangle(50,50,25,25)); 
     frame.add(drawExample); 
     frame.setSize(200,200); 
     frame.setVisible(true); 

    } 

    private void addRect(Rectangle rectangle) { 
     rctangles.add(rectangle); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.setColor(Color.WHITE); 
     g.fillRect(0, 0, getWidth(), getHeight()); 
     g.setColor(Color.BLACK); 
     for(Rectangle r : rctangles){ 
      g.fillRect(r.x, r.y, r.width,r.height); 
     } 
    } 

} 

enter image description here

+0

+1,用於List中自定義繪畫的簡單示例。 – camickr