因为是图片叠加,所以我用到了StackPane这个layout。
1 建一个imageview,把图片读进来。
2 建一个画板 canvas
3 建一个Stackpane stack。把imgview和canvas作为孩子加进去,特别要注意叠加的次序。
4 增加了一个清除按钮,用于清除canvas上面的点。画笔调用clearRect清除。
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
//Parent root = FXMLLoader.load(getClass().getResource("study.fxml"));
//layout
AnchorPane root = new AnchorPane();
final HBox hbox = new HBox();
hbox.setSpacing(100);
hbox.setAlignment(Pos.CENTER);//important
root.setTopAnchor(hbox, 20.0);
root.setLeftAnchor(hbox, 30.0);
root.setRightAnchor(hbox, 30.0);
root.setBottomAnchor(hbox, 20.0);
//control
Button btn1 = new Button();
btn1.setText("clear");
//image
Image img = new Image("file:images/body-image.jpg");
final ImageView imgview = new ImageView();
imgview.setFitHeight(300);
imgview.setFitWidth(300);
imgview.setImage(img);
//Canvas
final Canvas canvas = new Canvas(imgview.getFitWidth(),imgview.getFitHeight());
final GraphicsContext gc = canvas.getGraphicsContext2D();
//Stack Pane
final StackPane stack = new StackPane();
stack.setAlignment(Pos.CENTER);
stack.setPrefSize(imgview.getFitWidth(), imgview.getFitHeight());
stack.getChildren().add(imgview);
stack.getChildren().add(canvas);
hbox.setHgrow(btn1, Priority.ALWAYS);
hbox.setMargin(btn1, new Insets(0,0,10,10));
hbox.getChildren().add(btn1);
hbox.getChildren().add(stack);
root.getChildren().add(hbox);
//event
canvas.setOnMouseReleased(new EventHandler
() {
public void handle(MouseEvent e){
//Circle circle = new Circle(2,Color.RED);
gc.setFill(Color.RED);
double x = e.getX();
double y = e.getY();
gc.fillOval(x, y, 10, 10);
//stack.getChildren().add(canvas);
}
});
btn1.setOnMouseReleased(new EventHandler
(){
public void handle(MouseEvent e){
gc.clearRect(imgview.getX(), imgview.getY(),imgview.getFitWidth() ,imgview.getFitHeight());
}
});
Scene scene = new Scene(root,600,400);
primaryStage.initStyle(StageStyle.DECORATED);
primaryStage.setScene(scene);
primaryStage.setTitle("My_app");
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}