Search code examples
javagraphicsawtshapesjava-2d

How to create a new Shape out of two Ovals in AWT?


For my program, I want to have two ovals overlap and then create a new shape out of the overlapped area. So that I can later combine the resulting shape again with another shape.

In the end, I want to take the result and then color it differently. You can imagine the resulting image being a cluster of ovals where only certain parts of them are colored differently.

I am trying to do this with java.awt, but I can't really figure out how to create this new shape as some sort of object. I know there is a method called intersect(), but the way I understood it, it only checks if a shape intersects with a rectangle.


Solution

  • There is a class called Area (I believe it is in java.awt.geom) that would be perfect for this

    Shape oval1 = ..., oval2 = ...;
    Area a = new Area(oval1).subtract(oval2);
    

    You can color it how you want via

    Graphics2D g2 =...;
    g2.setColor(yourColor);
    g2.fill(a);
    

    And BTW, check out these controls for managing Areas here: https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/ui/shape/