Fill a rectangle with a pattern in Java Swing

I know how to fill a rectangle in Swing with solid color:

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

I know how to fill it with an image:

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

But how to fill a 950x950 rectangle with a 100x100 tile pattern?

(image image should be used 100 times)

+7
source share
2 answers

You are on the right track with setPaint . However, instead of setting it to color, you want to set it to a TexturePaint object.

From the Java tutorial :

The template for the TexturePaint class is defined by the BufferedImage class. To create a TexturePaint object, you specify an image that contains the pattern and the rectangle that is used to replicate and snap the pattern. The following image represents this function: example image

If you have a BufferedImage for the texture, create a TexturePaint like this:

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

where this rectangle represents the area of ​​the original image that you want to use.

The JavaDoc constructor is here .

Then run

 g2d.setPaint(tp); 

and you are good to go.

+10
source

As @wchargin said, you can use TexturePaint . Here is an example:

 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())); } } 
+2
source

All Articles