2014-04-03 152 views
3

假設我們有一個簡稱R如何在JavaFX中的矩形或圓圈內添加圖像?

Rectangle r = new Rectangle(40, 20); 

矩形和圖像稱爲圖像

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

如何適應矩形內的形象呢?另外,如果矩形也移動,我該如何移動圖像?我如何爲一個圓圈做同樣的事情?代碼示例非常感謝。

P.S. Jewelsea,我在等你,哈哈!

+0

可能重複的[圖像視圖上的邊界半徑和陰影](http://stackoverflow.com/questions/20489908/border-radius-and-shadow-on-imageview) – jewelsea

回答

4

,如果你想通過圖像來填充矩形,你可以按照這個: - 在FXML文件中添加一個圈

<Rectangle fx:id="imgMenuUser" /> 

而在你的控制器

@FXML 
private Rectangle rectangle; 
Image img = new Image("/image/rifat.jpg"); 
rectangle.setFill(new ImagePattern(img)); 
1

如何適合矩形內的圖像?

將形狀和圖像放入StackPane中。

另外,如果長方形也移動,我該如何移動圖像?

只要移動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); 
    } 
}