How do I add an image inside a rectangle or a circ

2019-06-27 18:57发布

Suppose we have a rectangle called r

Rectangle r = new Rectangle(40, 20);

and an image called image

Image image = new Image("...src for image");

How do I fit the image inside the rectangle? Also, how can I make the image move if the rectangle moves too? How do I do the same thing for a circle? Code examples are greatly appreciated.

P.S. Jewelsea, I'm waiting for you, lol!

2条回答
2楼-- · 2019-06-27 19:45

if you want to fill Rectangle by image, you can follow this:- in your fxml file add a Circle

<Rectangle fx:id="imgMenuUser" />

And in your Controller

@FXML
private Rectangle rectangle;
Image img = new Image("/image/rifat.jpg");
rectangle.setFill(new ImagePattern(img));
查看更多
可以哭但决不认输i
3楼-- · 2019-06-27 19:54

How do I fit the image inside the rectangle?

Put the shape and the image in a StackPane.

Also, how can I make the image move if the rectangle moves too?

Just move the StackPane.

import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Point2D;
import javafx.stage.Stage;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;


public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            Pane root = new Pane();

            StackPane imageContainer = new StackPane();
            ImageView image = new ImageView(...);
            imageContainer.getChildren().addAll(new Rectangle(64, 48, Color.CORNFLOWERBLUE), image);
            enableDragging(imageContainer);

            root.getChildren().add(imageContainer);

            Scene scene = new Scene(root,800,600);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    private void enableDragging(Node node) {
        final ObjectProperty<Point2D> mouseAnchor = new SimpleObjectProperty<>();
        node.setOnMousePressed( event -> mouseAnchor.set(new Point2D(event.getSceneX(), event.getSceneY())));
        node.setOnMouseDragged( event -> {
            double deltaX = event.getSceneX() - mouseAnchor.get().getX();
            double deltaY = event.getSceneY() - mouseAnchor.get().getY();
            node.relocate(node.getLayoutX()+deltaX, node.getLayoutY()+deltaY);
            mouseAnchor.set(new Point2D(event.getSceneX(), event.getSceneY()));;
        });
    }

    public static void main(String[] args) {
        launch(args);
    }
}
查看更多
登录 后发表回答