在javafx中对画布应用填充



我必须在javafx画布上逐点绘制正弦曲线,并将它们连接起来。但是,由于您可以将线的宽度更改为,有时会因为线靠近边界而在宽度上被剪切。那么,有没有可能喜欢做一个填充物或边界来避免这种情况呢?可以操纵坐标,但我不想这样做,因为我认为应该有更好的解决方案。画布图片

编辑:

这是在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();
}
}

如果要重置变换,例如,清除整个画布,包括填充区域,则需要重置变换。

将画布放置为StackPane,并在StackPane上设置填充。

Canvas canvas = new Canvas(715,495);
StackPane stackPane = new StackPane(canvas);
stackPane.setPadding(new Insets(5));

根据需要调整画布和填充大小。

最新更新