# 从几何图元构造复杂形状

> 原文： [https://docs.oracle.com/javase/tutorial/2d/advanced/complexshapes.html](https://docs.oracle.com/javase/tutorial/2d/advanced/complexshapes.html)

构造区域几何（CAG）是通过对现有几何形状执行布尔运算来创建新几何形状的过程。在 Java 2D API 中， [`Area`](https://docs.oracle.com/javase/8/docs/api/java/awt/geom/Area.html) 类实现 [`Shape`](https://docs.oracle.com/javase/8/docs/api/java/awt/Shape.html) 接口并支持以下布尔操作。

| ![Venn diagram showing Union](img/4e75256136509d13f578baa900242e32.jpg) | 联盟 | ![Venn diagram showing Subtraction](img/5ffb2a95b523f30f6da456896a9673be.jpg) | 减法 |
| ![Venn diagram showing Intersection](img/2c237bc5eaa2f2af4a3e028fe18a0424.jpg) | 路口 | ![Venn diagram showing Exclusive-or operation](img/36d24fe543c671024e323c5e599530ca.jpg) | 独家或（`XOR`） |

## 示例：区域

在此示例中，`Area`对象从几个椭圆构造一个梨形。

&lt;applet alt="applet constructs pear shape" archive="examples/lib/PearApplet.jar" code="Pear" height="200" width="150"&gt;&lt;param name="permissions" value="sandbox"&gt;&lt;/applet&gt;

* * *

**Note:**  If you don't see the applet running, you need to install at least the [Java SE Development Kit (JDK) 7](http://www.oracle.com/technetwork/java/javase/downloads/index.html) release.

* * *

[``Pear.java`` ](examples/Pear.java)包含此 applet 的完整代码。

通过在两个重叠的圆上执行交集来创建叶子。

```
leaf = new Ellipse2D.Double();
...
leaf1 = new Area(leaf);
leaf2 = new Area(leaf);
...
leaf.setFrame(ew-16, eh-29, 15.0, 15.0);
leaf1 = new Area(leaf);
leaf.setFrame(ew-14, eh-47, 30.0, 30.0);
leaf2 = new Area(leaf);
leaf1.intersect(leaf2);
g2.fill(leaf1);
...
leaf.setFrame(ew+1, eh-29, 15.0, 15.0);
leaf1 = new Area(leaf);
leaf2.intersect(leaf1);
g2.fill(leaf2);

```

重叠圆也用于通过减法操作构造茎。

```
stem = new Ellipse2D.Double();
...
stem.setFrame(ew, eh-42, 40.0, 40.0);
st1 = new Area(stem);
stem.setFrame(ew+3, eh-47, 50.0, 50.0);
st2 = new Area(stem);
st1.subtract(st2);
g2.fill(st1);

```

通过在圆形和椭圆形上进行联合操作来构造梨的主体。

```
circle = new Ellipse2D.Double();
oval = new Ellipse2D.Double();
circ = new Area(circle);
ov = new Area(oval);
...
circle.setFrame(ew-25, eh, 50.0, 50.0);
oval.setFrame(ew-19, eh-20, 40.0, 70.0);
circ = new Area(circle);
ov = new Area(oval);
circ.add(ov);
g2.fill(circ);

```