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

JavaFX Translation Transformation(平移转换)

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

平移将对象移动到屏幕上的不同位置。您可以通过将平移坐标(tx,ty)添加到原始坐标(X,Y)来转换2D中的点,以获得新坐标(X’,Y’)。

以下是在JavaFX中演示翻译的程序。在这里,我们在相同的位置创建2个圆(节点),具有相同的尺寸,但具有不同的颜色(棕色和Cadetblue)。我们也在使用cadetblue颜色的圆圈上应用翻译。

将此代码保存在名为TranslationExample.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
63
64
65
66
67
68
69
70
71
72
73
import javafx.application.Application; 
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.transform.Translate;
import javafx.stage.Stage;

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

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

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

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

//Setting the stroke width of the circle
circle.setStrokeWidth(20);

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

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

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

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

//Setting the stroke width of the circle
circle2.setStrokeWidth(20);

//Creating the translation transformation
Translate translate = new Translate();

//Setting the X,Y,Z coordinates to apply the translation
translate.setX(300);
translate.setY(50);
translate.setZ(100);

//Adding transformation to circle2
circle2.getTransforms().addAll(translate);

//Creating a Group object
Group root = new Group(circle,circle2);

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

//Setting title to the Stage
stage.setTitle("Translation transformation 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 TranslationExample.java 
java TranslationExample

执行时,上面的程序生成一个JavaFX窗口,如下所示。