【发布时间】:2020-02-17 20:00:33
【问题描述】:
JavaFX 坐标系从屏幕顶部绘制 Y 坐标,向下为正。我希望它是向上的,从屏幕底部开始。
需要翻译,需要翻转文本节点。
希望绘制的矩形能够以我们在数学课中“自然”的方式定位。以左下角为原点,向右上角扩展。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.*;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class FlippedExampleChart extends Application {
private LineChart<Number, Number> chart;
@Override
public void start(Stage primaryStage) throws Exception {
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
// Flip the axis
yAxis.setScaleY(-1);
// TODO How to translate to bottom of screen.
// TODO How to flip the text nodes.
this.chart = new LineChart<Number, Number>(xAxis, yAxis) {
@Override
public void layoutPlotChildren() {
super.layoutPlotChildren();
double height = yAxis.getDisplayPosition(100);
Rectangle r = new Rectangle(0, 0, 50, height);
r.setFill(Color.GREEN);
getPlotChildren().addAll(r);
}
};
this.chart.setAnimated(false);
VBox vbox = new VBox(this.chart);
Scene scene = new Scene(vbox, 400, 200);
primaryStage.setScene(scene);
primaryStage.setHeight(600);
primaryStage.setWidth(400);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
【问题讨论】:
-
这不是您所要求的,但
yAxis.getDisplayPosition(y)会将 y 轴刻度上的 y 值转换为坐标系中的值。所以不要对轴应用平移,只需在轴的坐标系中工作并使用该方法来转换变量。 -
@James_D 我熟悉这种方法。由于增加了心算开销,我想更进一步。
-
我想我假设您希望将矩形绘制在与轴相同的坐标中(即跨越
(0,0)到(50,100)沿常规图表轴)。但也许你真的想在像素坐标中工作(很难看到一个好的用例......)?困难在于使用Rectangles,因为您需要宽度和高度,而不是顶点的坐标。这是pretty straightforward 和其他形状。