JavaFX:将矩形转换为多边形

时间:2014-02-25 19:48:10

标签: java javafx-2 polygon rectangles

当用户试图点击其中一条边并将其拖到场景周围时,我希望将矩形转换为多边形。我开始使用以下代码对此进行简单的实现,但似乎我无法(至少在我的知识中)得到矩形/多边形的边缘以便于此操作。对此的任何意见都将不胜感激。

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;

class DrawPane extends Pane
{
public DrawPane(final Polygon poly)
{
    poly.setFill(Color.BEIGE);
    poly.setStroke(Color.CHARTREUSE);
    poly.setStrokeWidth(1);

    setDragHandler(poly);

    getChildren().addAll(poly);
}

private double dragDeltaX, dragDeltaY;

private void setDragHandler(final Polygon poly)
{
    poly.setOnMousePressed(new EventHandler<MouseEvent>()
    {
        @Override
        public void handle(MouseEvent mouseEvent)
        {
            dragDeltaX = poly.getLayoutX()
                - mouseEvent.getSceneX();
            dragDeltaY = poly.getLayoutY()
                - mouseEvent.getSceneY();
        }
    });

    poly.setOnMouseDragged(new EventHandler<MouseEvent>()
    {
        @Override
        public void handle(MouseEvent mouseEvent)
        {
            poly.setRotate(dragDeltaX
                + dragDeltaY);
            poly.setCursor(Cursor.MOVE);
        }
    });

    poly.setOnMouseEntered(new EventHandler<MouseEvent>()
    {
        @Override
        public void handle(MouseEvent mouseEvent)
        {
            poly.setCursor(Cursor.HAND);
        }
    });

    poly.setOnMouseReleased(new EventHandler<MouseEvent>()
    {
        @Override
        public void handle(MouseEvent mouseEvent)
        {
            poly.setCursor(Cursor.HAND);
        }
    });
}
}


public class Rectangle2Polygon extends Application
{
@Override
public void start(Stage stage)
{

    Polygon poly = new Polygon(10, 10, 100, 10, 100, 100, 10, 100);

    stage.setScene(new Scene(new DrawPane(poly), 450, 300));
    stage.show();
}

public static void main(String[] args)
{
    launch(args);
}
}

1 个答案:

答案 0 :(得分:1)

您可以使用此方法:

  1. 将矩形拆分为顶点和侧面
  2. 代码顶点可拖动
  3. 使边绑定到顶点
  4. 我根据默认Ensemble example编写了一个小型演示:

    https://gist.github.com/sgrinev/9238167

    你可以拖动这个“矩形”的顶点来实现这样的结果:

    enter image description here