gpt4 book ai didi

java - 在 javafx 中将填充应用于 Canvas

转载 作者:行者123 更新时间:2023-12-02 01:28:28 26 4
gpt4 key购买 nike

我必须在 javafx canvas 中逐点绘制正弦曲线并将它们连接起来。但是,由于您可以更改线条的宽度,因此有时会因为线条靠近边界而宽度被削减。那么是否有可能通过填充或边框来避免这种情况呢?可以操纵坐标,但说实话我不想这样做,因为我认为应该有更好的解决方案。 Picture of the canvas

编辑:

这是在 javafx 项目中重现它的代码示例

public class HelloApplication extends Application {

@Override
public void start(Stage stage) throws IOException {
Canvas c = new Canvas(715,495);
GraphicsContext gc = c.getGraphicsContext2D();
VBox v = new VBox();
Pane p = new Pane();
p.getChildren().add(c);


Button b1 = new Button("Draw Sinus at Canvas");
b1.setOnAction(e -> drawSinus(c, gc));

v.getChildren().addAll(b1, p);
Scene sc = new Scene(v);
stage.setScene(sc);
stage.setTitle("Drawing Lines - Dynamically at Runtime");
stage.show();
}


private void drawSinus(Canvas c, GraphicsContext gc) {
double height = c.getHeight();
double width = c.getWidth();
double multiplier = (2 * Math.PI)/width;
double x1 = 0;
double y1 = height/2;
double x2 = 1;
double y2 = 0;
int i = 0;
gc.setStroke(Color.BLACK);
gc.setLineWidth(10);

while(i < width) {
y2 = (height/2) - ((height/2) * Math.sin(x2 * multiplier));
gc.strokeLine(x1,y1,x2,y2);
x1 = x2;
y1 = y2;
x2++;
i++;
}
}

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

最佳答案

在您正在绘制的区域周围添加一些填充而不更改您使用的坐标的一种方法是向图形上下文添加变换。基本上,您首先按比率 (width-2*padding)/width(height-2*padding)/height 缩放绘图区域,使其变小(因此实际绘图区域在每个维度上都会减少 2*padding 大小)。然后在每个维度中通过 padding 进行翻译。这看起来像:

public class HelloApplication extends Application {

@Override
public void start(Stage stage) throws IOException {
Canvas c = new Canvas(715,495);
GraphicsContext gc = c.getGraphicsContext2D();
VBox v = new VBox();
Pane p = new Pane();
p.getChildren().add(c);


Button b1 = new Button("Draw Sinus at Canvas");
b1.setOnAction(e -> drawSinus(c, gc, 10));

v.getChildren().addAll(b1, p);
Scene sc = new Scene(v);
stage.setScene(sc);
stage.setTitle("Drawing Lines - Dynamically at Runtime");
stage.show();
}


private void drawSinus(Canvas c, GraphicsContext gc, double padding) {


double height = c.getHeight();
double width = c.getWidth();

Affine transform = new Affine(Transform.scale((width-2*padding)/width, (height-2*padding)/height));
transform.appendTranslation(padding, padding);
gc.setTransform(transform);

double multiplier = (2 * Math.PI)/width;
double x1 = 0;
double y1 = height/2;
double x2 = 1;
double y2 = 0;
int i = 0;
gc.setStroke(Color.BLACK);
gc.setLineWidth(10);

while(i < width) {
y2 = (height/2) - ((height/2) * Math.sin(x2 * multiplier));
gc.strokeLine(x1,y1,x2,y2);
x1 = x2;
y1 = y2;
x2++;
i++;
}

// reset transform; may not be necessary depending on actual use case
gc.setTransform(new Affine());
}

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

如果您想要清除整个 Canvas (包括填充区域),则需要重置变换。

关于java - 在 javafx 中将填充应用于 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73870876/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com