Reputation: 274
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.
Upvotes: 5
Views: 2149
Reputation: 2682
The math is this:
if you know the circle is at (x, y) and has radius r
for(i=0; i<width; i++)
for(j=0; j<height; j++)
if((i-x)*(i-x)+(j-y)*(j-y))>r*r)
b.setRGB(i, j, 0xff0000);
This will paint BufferedImage b red outside the circle.
Upvotes: 0
Reputation: 17524
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) :
With crop (outer part filled with black) :
Upvotes: 3
Reputation: 1
What if you were to make the background a solid color and and you left the inner of the oval white?
JPanel.setBackgroundColor(Color.black);
then draw and fill your oval
g2d.setColor(Color.white);
g2d.drawOval(x, y, width, height);
g2d.fillOval(x, y, width, height);
this should work to contrast them for an example
Upvotes: 0