10

I know how to fill a rectangle in Swing with a 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 rectangle of size 950x950 with some tiled pattern of size 100x100?

(pattern image should be used 100 times)

4
  • put every elements to the array (in proper ordering), then loop inside array
    – mKorbel
    Mar 10, 2013 at 20:32
  • for better help sooner post an SSCCE, short, runnable, compilable
    – mKorbel
    Mar 10, 2013 at 20:33
  • 2
    Have you tried using a TexturePaint object for this? Mar 10, 2013 at 20:33
  • @HovercraftFullOfEels No, I haven't known about it, thank you! Mar 10, 2013 at 20:36

2 Answers 2

13

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

From the Java tutorial:

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

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

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

where the given rectangle represents the area of the source image you want to tile.

The constructor JavaDoc is here.

Then, run

g2d.setPaint(tp);

and you're good to go.

2
  • is it possible to randomize the positions a little bit?
    – wutzebaer
    Feb 15, 2015 at 13:39
  • @wutzebaer Not with a texture paint, no. There isn't a concept of "positions" (of, presumably, the circles); the circles are just part of the image, which gets tiled. If you actually want this specific pattern but with randomized circles, you could draw it procedurally: first fill your canvas with the background color, then fill rows of circles, and perturb them slightly from the nominal positions.
    – wchargin
    Feb 15, 2015 at 15:52
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.