2013-03-10 91 views
7

我知道如何填充矩形在Swing用純色:填充矩形中的Java Swing模式

Graphics2D g2d = bi.createGraphics(); 
g2d.setColor(Color.RED); 
g2d.fillRect(0,0,100,100); 

我知道如何使用圖像填充:

BufferedImage bi; 
Graphics2D g2d = bi.createGraphics(); 
g2d.setPaint (new Color(r, g, b)); 
g2d.fillRect (0, 0, bi.getWidth(), bi.getHeight()); 

但如何用尺寸爲100x100的平鋪圖案填充尺寸爲950x950的矩形?

(圖形圖像應使用100次)

+0

把每一個元件以陣列(在適當的順序),然​​後內部陣列 – mKorbel 2013-03-10 20:32:18

+0

環爲更好地幫助更快張貼[SSCCE](http://sscce.org/),短,可運行,可編譯 – mKorbel 2013-03-10 20:33:29

+2

您是否嘗試過使用[TexturePaint](http://docs.oracle.com/javase/7/docs/api/java/awt/TexturePaint.html)對象? – 2013-03-10 20:33:35

回答

10

你是正確的軌道上setPaint。但是,不要將其設置爲某種顏色,而要將其設置爲TexturePaint對象。

the Java tutorial

用於TexturePaint類的圖案由BufferedImage類定義。要創建TexturePaint對象,請指定包含該圖案的圖像和用於複製和定位該圖案的矩形。下面的圖像表示此功能: example image

如果您對紋理BufferedImage,創建TexturePaint像這樣:

TexturePaint tp = new TexturePaint(myImage, new Rectangle(0, 0, 16, 16)); 

中給定的矩形表示要對源圖像的區域平鋪。

構造函數JavaDoc是here

然後,運行

g2d.setPaint(tp); 

,你是好去。

+0

是的,這應該解決OP的問題。 1+ – 2013-03-10 20:40:42

+0

非常感謝! – 2013-03-10 20:49:34

+0

對於[示例](http://stackoverflow.com/a/11556441/230513)。 – trashgod 2013-03-11 00:40:10

2

正如@wchargin所說,你可以使用TexturePaint。下面是一個例子:

public class TexturePanel extends JPanel { 

    private TexturePaint paint; 

    public TexturePanel(BufferedImage bi) { 
     super(); 
     this.paint = new TexturePaint(bi, new Rectangle(0, 0, bi.getWidth(), bi.getHeight())); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     Graphics2D g2 = (Graphics2D) g; 
     g2.setPaint(paint); 
     g2.fill(new Rectangle(0, 0, getWidth(), getHeight())); 
    } 
}