使用鼠标在ImageView上绘图的任何方法都不知道,例如使用画布? 感谢
答案 0 :(得分:7)
我来到这里是对我的问题的一个很好的解决方案..不是吗?
AnchorPane anchorRoot;
double initX;
double initY;
ImageView iv = new ImageView(image);
final double maxX = iv.getImage().getWidth();
final double maxY = iv.getImage().getHeight();
anchorRoot.getChildren().add(iv);
iv.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
//System.out.println("Clicked, x:" + me.getSceneX() + " y:" + me.getSceneY());
//the event will be passed only to the circle which is on front
initX = me.getSceneX();
initY = me.getSceneY();
me.consume();
}
});
iv.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
//System.out.println("Dragged, x:" + me.getSceneX() + " y:" + me.getSceneY());
if (me.getSceneX() < maxX && me.getSceneY() < maxY) {
Line line = new Line(initX, initY, me.getSceneX(), me.getSceneY());
line.setFill(null);
line.setStroke(Color.RED);
line.setStrokeWidth(2);
anchorRoot.getChildren().add(line);
}
initX = me.getSceneX() > maxX ? maxX : me.getSceneX();
initY = me.getSceneY() > maxY ? maxY : me.getSceneY();
}
});
答案 1 :(得分:0)
您可以使用javafx轻松完成此操作(未显示设计文件(fxml),只显示代码的工作原理)...
package sample;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller implements Initializable{
@FXML private ImageView img;
@Override
public void initialize(URL location, ResourceBundle resources) {
Image[] i={null};
i[0]=new Image("file:\\"+"C:\\Users\\Ragib\\Desktop\\a.jpg");
img.setFitHeight(i[0].getHeight());
img.setFitWidth(i[0].getWidth());
img.setImage(i[0]);
img.setOnMouseDragged(event -> {
double x=event.getX();
double y=event.getY();
WritableImage wi=new WritableImage(i[0].getPixelReader(),(int)i[0].getWidth(),(int)i[0].getHeight());
PixelWriter pw=wi.getPixelWriter();
pw.setColor((int)x,(int)y,new Color(0,0,0,1));
i[0]=wi;
img.setImage(i[0]);
});
}
}