How to Fill Color Outside of a Shape (an Oval)

Anju Maaka :

I want to be able to draw on a BufferedImage, using a Graphics2D instance, and fill Color outside of a Shape. If this was a shape such as a Rectangle it would be easy, but the Shape I need to work with is a Circle.

It's easy to fill a circle with Color, just by writing:

Graphics2D g2d = <my_image>.createGraphics();
...
g2d.fillOval(x, y, width, height);

However, what I want is the opposite of this. Instead of filling the inside of the oval defained by the numbers (x, y, width, height) I want to fill everything outside of it.

I have had very little success with this. The only thing that even comes to mind would be drawing HUGE arches around the space I want the circle to occupy, by I'm having a hard time figuring out the math to calculate that.

EDIT: The reason why I cannot just fill the whole image and then paint the circle after, is because what's to be in the circle is not a single color, but rather I want to take an image (any image, like a photo of myself) and be able to add a single color around a circle in the middle of that image. So whatever is in the middle of the circle is already there before painting around it, and it's not something painted by code in the first place.

Arnaud :

Here is an example based on the answer from Java anti fillRect (fill everything outside of said rectangle).

It uses the substract method from java.awt.geom.Area .

        Area outter = new Area(new Rectangle(0, 0, img.getWidth(), img.getHeight()));
        int x = (img.getWidth() / 4) ;
        int y = (img.getHeight() / 4);
        Ellipse2D.Double inner = new Ellipse2D.Double(x,y, img.getWidth()/2, img.getHeight()/2);
        outter.subtract(new Area(inner));// remove the ellipse from the original area

        g2d.setColor(Color.BLACK);
        g2d.fill(outter);

Without crop (i.e without the g2d.fill(outter) part) :

enter image description here

With crop (outer part filled with black) :

enter image description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=83596&siteId=1