我在缩放包含形状的组并拖动形状时遇到问题。
在下面的例子中,我有一个包含2个矩形的组,在缩放组后,如果我拖动其中一个矩形,另一个将负向另一个的距离,即,如果我将矩形r2向下拖动,矩形r会上升等等
我想知道这是不是某种错误,或问题是什么?
下面的代码是我的问题的一个工作示例。
注意:我对边界进行了测试,只有当拖动的矩形移出当前边界时才会发生变化。
如果向右移动,新边界将类似于
BoundingBox [minX:250.0, minY:250.0, minZ:0.0, width:301.7606201171875, height:338.6553955078125, depth:0.0, maxX:551.7606201171875, maxY:588.6553955078125, maxZ:0.0]
即使另一个矩形移动到minX
和minY
边界之外。
import javafx.scene.shape.Rectangle;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class SampleScale extends Application {
@Override
public void start(Stage primaryStage) {
Group g = new Group();
Rectangle r = new Rectangle(250,250,10,10);
Rectangle r2 = new Rectangle(260,260,10,10);
r2.setFill(Color.RED);
r2.setOnMouseDragged(event
->
{
r2.setTranslateX(r2.getTranslateX() + (event.getX() -r2.getX()));
r2.setTranslateY(r2.getTranslateY() + (event.getY() -r2.getY()));
g.autosize();
event.consume();
});
Pane p = new Pane();
p.setPrefSize(1000, 1000);
g.getChildren().addAll(r,r2);
p.getChildren().addAll(g);// comment out to test bottom code;
//default works
//g.setScaleX(1);
//g.setScaleY(1);
//causes other node to move negative distance of the other object
// i.e., if r2 is dragged down, r will move up, etc.
g.setScaleX(2);
g.setScaleY(2);
//-------------------------
//this works if not placed inside a group
// p.getChildren().addAll(r,r2);
// r.setScaleX(2);
// r.setScaleY(2);
// r2.setScaleX(2);
// r2.setScaleY(2);
Scene scene = new Scene(p, 1300, 1250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
scaleX
和scaleY
属性使用节点的中心作为缩放的枢轴点。由于移动r2
调整Group
,其他孩子也移动。
您可以使用轴心点Scale
来应用(0, 0)
变换:
// g.setScaleX(2);
// g.setScaleY(2);
g.getTransforms().add(new Scale(2, 2, 0, 0));