简体   繁体   中英

JavaFX Polygon Translation, Rotation, Scaling and its Points

I ran into a strange issue with the polygon class from javafx (java 8). When I apply a set translate, rotate or scale on the polygon instance it is correctly moving the polygon around on my shape. The problem is, the points in the getPoints() method stay the same. I started now to create my own methods and moving around the points and resetting them, the methods do what they should, but is it the right way?

Here an example:

private void translatePoints(double translateX, double translateY) {
    List<Double> newPoints = new ArrayList<>();
    for (int i = 0; i < getPoints().size(); i += 2) {
        newPoints.add(getPoints().get(i) + translateX);
        newPoints.add(getPoints().get(i + 1) + translateY);
    }
    getPoints().clear();
    getPoints().addAll(newPoints);
}

Is there a way to get the translated, rotated and scaled points after a couple of operations?

Or do I have to implement them all separatly?

Take a look at the subclasses of Transform ( Affine , Rotate , Scale , Shear and Translate ). They allow you to transform points stored in a double[] array using the transform2DPoints method.

double[] points = new double[] {
    0, 0,
    0, 1,
    1, 1,
    1, 0
};
Rotate rot = new Rotate(45, 0.5, 0.5);
Translate t = new Translate(5, 7);
Scale sc = new Scale(3, 3);

for (Transform transform : Arrays.asList(rot, t, sc)) {
    transform.transform2DPoints(points, 0, points, 0, 4);
}

System.out.println(Arrays.toString(points));

this way you need to take care of determining the pivot point of transforms where this is relevant on your own.

You could also get resulting transform for a node using Node.getLocalToParentTransform .

double[] points = polygon.getPoints().stream().mapToDouble(Number::doubleValue).toArray();
polygon.getLocalToParentTransform().transform2DPoints(points, 0, points, 0, points.length/2);
System.out.println(Arrays.toString(points));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM