JavaFx 8 - Scaling / zooming ScrollPane relative to mouse position
Asked Answered
S

4

9

I need to zoom in / out on a scroll pane, relative to the mouse position.

I currently achieve the zooming functionality by wrapping my content in a Group, and scaling the group itself. I create a new Scale object with a custom pivot. (Pivot is set to the mouse position)

This works perfectly for where the Group's initial scale is 1.0, however scaling afterwards does not scale in the correct direction - I believe this is because the relative mouse position changes when the Group has been scaled.

My code:

@Override
public void initialize(URL location, ResourceBundle resources) {

    Delta initial_mouse_pos = new Delta();

    anchorpane.setOnScrollStarted(event -> {
        initial_mouse_pos.x = event.getX();
        initial_mouse_pos.y = event.getY();
    });

    anchorpane.setOnScroll(event -> {
        double zoom_fac = 1.05;
        double delta_y = event.getDeltaY();

        if(delta_y < 0) {
            zoom_fac = 2.0 - zoom_fac;
        }

        Scale newScale = new Scale();
        newScale.setPivotX(initial_mouse_pos.x);
        newScale.setPivotY(initial_mouse_pos.y);
        newScale.setX( content_group.getScaleX() * zoom_fac );
        newScale.setY( content_group.getScaleY() * zoom_fac );

        content_group.getTransforms().add(newScale);

        event.consume();
    });
}

private class Delta { double x, y; }

How do I get the correct mouse position at different levels of scaling? Is there a completely different way to zooming the ScrollPane that is easier?

Serafinaserafine answered 3/10, 2016 at 9:2 Comment(1)
Here is the code I use for dynamic node scaling.Hadlee
B
23

This is a scalable, pannable JavaFX ScrollPane :

import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;

public class ZoomableScrollPane extends ScrollPane {
    private double scaleValue = 0.7;
    private double zoomIntensity = 0.02;
    private Node target;
    private Node zoomNode;

    public ZoomableScrollPane(Node target) {
        super();
        this.target = target;
        this.zoomNode = new Group(target);
        setContent(outerNode(zoomNode));

        setPannable(true);
        setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        setFitToHeight(true); //center
        setFitToWidth(true); //center

        updateScale();
    }

    private Node outerNode(Node node) {
        Node outerNode = centeredNode(node);
        outerNode.setOnScroll(e -> {
            e.consume();
            onScroll(e.getTextDeltaY(), new Point2D(e.getX(), e.getY()));
        });
        return outerNode;
    }

    private Node centeredNode(Node node) {
        VBox vBox = new VBox(node);
        vBox.setAlignment(Pos.CENTER);
        return vBox;
    }

    private void updateScale() {
        target.setScaleX(scaleValue);
        target.setScaleY(scaleValue);
    }

    private void onScroll(double wheelDelta, Point2D mousePoint) {
        double zoomFactor = Math.exp(wheelDelta * zoomIntensity);

        Bounds innerBounds = zoomNode.getLayoutBounds();
        Bounds viewportBounds = getViewportBounds();

        // calculate pixel offsets from [0, 1] range
        double valX = this.getHvalue() * (innerBounds.getWidth() - viewportBounds.getWidth());
        double valY = this.getVvalue() * (innerBounds.getHeight() - viewportBounds.getHeight());

        scaleValue = scaleValue * zoomFactor;
        updateScale();
        this.layout(); // refresh ScrollPane scroll positions & target bounds

        // convert target coordinates to zoomTarget coordinates
        Point2D posInZoomTarget = target.parentToLocal(zoomNode.parentToLocal(mousePoint));

        // calculate adjustment of scroll position (pixels)
        Point2D adjustment = target.getLocalToParentTransform().deltaTransform(posInZoomTarget.multiply(zoomFactor - 1));

        // convert back to [0, 1] range
        // (too large/small values are automatically corrected by ScrollPane)
        Bounds updatedInnerBounds = zoomNode.getBoundsInLocal();
        this.setHvalue((valX + adjustment.getX()) / (updatedInnerBounds.getWidth() - viewportBounds.getWidth()));
        this.setVvalue((valY + adjustment.getY()) / (updatedInnerBounds.getHeight() - viewportBounds.getHeight()));
    }
}
Betteanne answered 1/6, 2017 at 18:16 Comment(3)
Great, worked for me. Also: I'd recommend wrapping the content of outerNode.setOnScroll(e -> {...} in a if (e.isControlDown()) {...}, that way the ability to scroll up and down is preserved.Obstetric
@DanielHári Thank you so much bro. Worked perfectlyObstacle
In my case the event listener wasn't called. I had to set the listener using addEventFilter() directly on the ZoomableScrollPane as described in this answer https://mcmap.net/q/358670/-zooming-in-javafx-scrollevent-is-consumed-when-content-size-exceeds-scrollpane-viewport. This also fixed the issue of the ScrollEvent not being consumed when content size exceeds ScrollPane viewport. Other than that it works, thank you.Dodge
R
1

Assuming you want to have the following zoom behavior: When the mouse wheel is pushed forward/backward the object under the cursor will be scaled up/down and the area under the cursor is now centered within the zooming area. Eg. pushing the wheel forward while pointing at a place left from the center of the zooming area results in a 'up-scale and move right' action.

The scaling thing is as simple as you have already done so far. The tricky part is the move action. There are some problem you have to consider within your calculations:

  1. You have to calculate the difference from the center and the position of the cursor. You can calculate this value by subtracting the center point (cp) from the mouse position (mp).

  2. If your zoom level is 1 and you point 50px left from the center you want to move your object 50px to the right, because 1px of your screen corresponds to one 1px of your object (picture). But if you doubled the size of your object, than 2 screen pixel are equal to on object pixel. You have to consider this when moving the object, because the translating part is always done before the scaling part. In other words you are moving your object in original size and the scaling is only the second independent step.

  3. How is the scaling done? In JavaFX you simply set some scale-properties and JavaFX does the rest for you. But what does it exactly? The important thing to know is, where the fixed point is while zooming the object. If you scale an object there will be one point which stays fixed at its position while all other points are moving towards this point or moving way from it. As the documentation of JavaFX says the center of the zoomed object will be the fixed point.

Defines the factor by which coordinates are scaled about the center of the object along the X axis of this Node.

That means you have to ensure that your visual center point is equal to the one JavaFX uses while scaling you object. You can achieve this if you wrap your object within a container. Now zoom the container instead of the object and position the object within the container to fit your needs.

I hope this helps. If you need more help please offer a short working example project.

Roye answered 4/10, 2016 at 12:56 Comment(0)
X
1

Did you try to remove the setOnScrollStarted-event and move its content to the setOnScroll-event?

Doing so reduces the need of your extra Delta-class and the computations of your mouse-positions are always on par with the current zoom factor.

I implemented the same thing and it works the way you are describing it.

Somehow like this:

@Override
public void initialize(URL location, ResourceBundle resources) {

    anchorpane.setOnScroll(event -> {
        double zoom_fac = 1.05;

        if(delta_y < 0) {
            zoom_fac = 2.0 - zoom_fac;
        }

        Scale newScale = new Scale();
        newScale.setPivotX(event.getX);
        newScale.setPivotY(event.getY);
        newScale.setX( content_group.getScaleX() * zoom_fac );
        newScale.setY( content_group.getScaleY() * zoom_fac );

        content_group.getTransforms().add(newScale);

        event.consume();
    });
}
Xanthine answered 25/10, 2016 at 9:42 Comment(0)
M
0

I believe this is a duplicate of this question which involves the same concepts at work. If you don't really care if it zooms relative to your mouse and just prefer it zoom in the center look at this question. If you need any more help comment below.

Meraree answered 3/10, 2016 at 21:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.