我使用下面的代码在JavaFX Canvas上绘制垂直线。不知何故,最后一行(最后10%)的不透明度较低。我没有改变任何选项(转换/效果对gc)。我附上截图供参考,任何想法?
public class ChartPane extends StackPane {
Canvas canvas;
public ChartPane() {
setStyle("-fx-background-color: white;");
canvas = new Canvas(getWidth(), getHeight());
getChildren().add(canvas);
widthProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
canvas.setWidth(newValue.intValue());
}
});
heightProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
canvas.setHeight(newValue.intValue());
}
});
}
@Override
protected void layoutChildren() {
super.layoutChildren();
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.save();
gc.clearRect(0, 0, getWidth(), getHeight());
System.out.println(getWidth() + ", " + getHeight());
// vertical lines
gc.setStroke(Color.BLUE);
gc.setLineWidth(0.1);
gc.beginPath();
for(int i = 0 ; i < getWidth() ; i+=30){
gc.moveTo(i, 0);
gc.lineTo(i, getHeight() - (getHeight()%30));
gc.stroke();
}
// horizontal lines
gc.beginPath();
gc.setStroke(Color.RED);
for(int i = 30 ; i < getHeight() ; i+=30){
gc.moveTo(30, i);
gc.lineTo(getWidth(), i);
gc.stroke();
}
//gc.restore();
}
}
答案 0 :(得分:2)
我已将代码重写为strokeLine
,似乎有效:
@Override
protected void layoutChildren() {
super.layoutChildren();
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.clearRect(0, 0, getWidth(), getHeight());
// vertical lines
gc.setStroke(Color.BLUE);
for(int i = 0 ; i < getWidth() ; i+=30){
gc.strokeLine(i, 0, i, getHeight() - (getHeight()%30));
}
// horizontal lines
gc.setStroke(Color.RED);
for(int i = 30 ; i < getHeight() ; i+=30){
gc.strokeLine(30, i, getWidth(), i);
}
}
Fyi,我使用Canvas编写了一个可调整大小的网格:https://gist.github.com/eckig/176b7c2a10048bb71f43
<强>更新强> 我从我的链接示例中复制了用Sharp线条绘制并显示在哪里编辑线宽:
@Override
protected void layoutChildren() {
super.layoutChildren();
final int top = (int) snappedTopInset();
final int right = (int) snappedRightInset();
final int bottom = (int) snappedBottomInset();
final int left = (int) snappedLeftInset();
final int width = (int) getWidth() - left - right;
final int height = (int) getHeight() - top - bottom;
final double spacing = 30;
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.clearRect(0, 0, getWidth(), getHeight());
gc.setLineWidth(1); // change the line width
final int hLineCount = (int) Math.floor((height + 1) / spacing);
final int vLineCount = (int) Math.floor((width + 1) / spacing);
gc.setStroke(Color.RED);
for (int i = 0; i < hLineCount; i++) {
gc.strokeLine(0, snap((i + 1) * spacing), width, snap((i + 1) * spacing));
}
gc.setStroke(Color.BLUE);
for (int i = 0; i < vLineCount; i++) {
gc.strokeLine(snap((i + 1) * spacing), 0, snap((i + 1) * spacing), height);
}
}
private double snap(double y) {
return ((int) y) + 0.5;
}