Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill rectangle with pattern in Java Swing

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)

like image 248
Edward Ruchevits Avatar asked Mar 10 '13 20:03

Edward Ruchevits


People also ask

How do you fill a rectangle in Java?

Draw rectangles, use the drawRect() method. To fill rectangles, use the fillRect() method : Shape « 2D Graphics GUI « Java.

How do you fill a shape with color in Java?

To fill rectangles with the current colour, we use the fillRect() method. In the example we draw nine coloured rectangles. Graphics2D g2d = (Graphics2D) g; There is no need to create a copy of the Graphics2D class or to reset the value when we change the colour property of the graphics context.

How do you make a rectangle rounded in Java?

We can use the drawRoundRect() method that accepts x-coordinate, y-coordinate, width, height, arcWidth, and arc height to draw a rounded rectangle.

How do you draw a rectangle in a Jframe?

In Java, to draw a rectangle (outlines) onto the current graphics context, we can use the following methods provided by the Graphics/Graphics2D class: drawRect(int x, int y, int width, int height) draw3DRect(int x, int y, int width, int height, boolean raised) draw(Rectangle2D)


1 Answers

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.

like image 66
wchargin Avatar answered Oct 04 '22 05:10

wchargin