Kyranstar
Kyranstar

Reputation: 1720

Clip a BufferedImage to an Area

I'm trying to draw an image within a certain area. Right now I have code that fills an area with a RadialGradientPaint.

Area lightArea = ...
// fill the polygon with the gradient paint
g.setPaint(light.paint);
g.fill(lightArea);

I would like to draw a BufferedImage in that area instead of drawing a RadialGradientPaint. Is there a way I can do that?

Upvotes: 3

Views: 1418

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347204

You could use BufferdImage#getSubimage

Rectangle bounds = area.getBounds();
BufferedImage img = master.getSubImage(0, 0, Math.min(bounds.width, master.getWidth()), Math.min(bounds.height, master.getHeight());

This assumes that the area is rectangular. If it's not, you cold create a mask image, based on the shape of the Area and use it to generate masked image (cookie cutting the image out of the shape)

As demonstrated here. The benefit of which is it allows for antialiasing

Upvotes: 2

Adrian Leonhard
Adrian Leonhard

Reputation: 7360

Use Graphics.setClip:

g.setClip(lightArea);
g.drawImage(yourImage, x, y, null);

See http://docs.oracle.com/javase/tutorial/2d/advanced/clipping.html for more details.

Upvotes: 2

Related Questions