多读书多实践,勤思考善领悟

JavaFX 2D Shapes union形状(对象)联合操作(Union Operation)

本文于1807天之前发表,文中内容可能已经过时。

此操作将两个或多个形状作为输入,并返回它们占用的区域,如下所示。

您可以使用名为union()的方法对形状执行并集操作。由于这是一个静态方法,您应该使用类名(Shape或其子类)来调用它,如下所示。

1
Shape shape = Shape.subtract(circle1, circle2);

以下是联合操作的示例。在这里,我们绘制两个圆并对它们执行并集操作。将此代码保存在名为unionExample.java的文件中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import javafx.application.Application; 
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Shape;

public class UnionExample extends Application {
@Override
public void start(Stage stage) {
//Drawing Circle1
Circle circle1 = new Circle();

//Setting the position of the circle
circle1.setCenterX(250.0f);
circle1.setCenterY(135.0f);

//Setting the radius of the circle
circle1.setRadius(100.0f);

//Setting the color of the circle
circle1.setFill(Color.DARKSLATEBLUE);

//Drawing Circle2
Circle circle2 = new Circle();

//Setting the position of the circle
circle2.setCenterX(350.0f);
circle2.setCenterY(135.0f);

//Setting the radius of the circle
circle2.setRadius(100.0f);

//Setting the color of the circle
circle2.setFill(Color.BLUE);

//Performing union operation on the circle
Shape shape = Shape.union(circle1, circle2);

//Setting the fill color to the result
shape.setFill(Color.DARKSLATEBLUE);

//Creating a Group object
Group root = new Group(shape);

//Creating a scene object
Scene scene = new Scene(root, 600, 300);

//Setting title to the Stage
stage.setTitle("Union Example");

//Adding scene to the stage
stage.setScene(scene);

//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}

使用以下命令从命令提示符编译并执行保存的java文件。

1
2
javac UnionExample.java 
java UnionExample

执行时,上面的程序生成一个显示以下输出的JavaFX窗口 -