Reputation: 3735
I am new to javafx, and I'm programming a game using its rendering functions, specifically, GraphicsContext.fillArc()
and the like in eclipse.
This is my current code:
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
scene.getStylesheets()
.add(getClass().getResource("application.css").toExternalForm());
Canvas canvas = new Canvas(400, 400);
root.getChildren().add(canvas);
GraphicsContext gc = canvas.getGraphicsContext2D();
new AnimationTimer()
{
public void handle(long currentNanoTime)
{
gc.setFill(Color.BLUE);
gc.fillArc(150, 150, 100, 100, 0, 240, ArcType.ROUND);
}
}.start();
primaryStage.show();
However the fillArc()
method renders a shape on my screen with ragged edges. I want antialiasing to be applied so that the edges are smoothed. However I cannot find any related methods in GraphicsContext
class, and changing the instantiation of scene
to new Scene(root, 400, 400, false, SceneAntialiasing.BALANCED);
has no effect as well. So my question is how to achieve antialiasing on GraphicsContext.fillArc()
or whether it's fundamentally possible?
Also I'm very new to javafx and cgi in general, so any suggestions and recommendations are welcomed.
Update:
As suggested by @jewelsea, when the code block gc.setFill(Color.BLUE);
gc.fillArc(150, 150, 100, 100, 0, 240, ArcType.ROUND);
is placed outside of the anonymous subclass of AnimationTimer
, the rendered image is antialiased. Neither of us can figure out why as of now. FYI.
Upvotes: 4
Views: 1653
Reputation: 1526
I encountered a similar problem while playing around with Canvas
and AnimationTimer
. An important key to the solution is the comment posted by @jewelsea:
"... if you comment out the animation timer and just draw the arc without it, then the arc is nicely antialiased ..."
This basically means, if we draw the arc once it is antialiased. But if we draw it in the handle()
method of the AnimationTimer
, it is drawn 60 times per second. The results can be seen better after adding a long sleep to the handle()
method. The first time the circle is rendered on a white background and looks as desired. The second time a blue circle is rendered on top of the previous blue circle. The pixels which were colored partially blue because of antialiasing, become darker. The same happens when the circle is drawn the third time, and so on. The following image shows a magnified portion of the arc after 1, 2, 3, 4, 5, 10, and 50 iterations:
A simple solution to the problem is to fill the canvas with the background color, before rendering anything:
public void handle(long currentNanoTime) {
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
gc.setFill(Color.BLUE);
gc.fillArc(150, 150, 100, 100, 0, 240, ArcType.ROUND);
}
Upvotes: 4