Canvas does not draw smooth lines

自古美人都是妖i 提交于 2019-12-01 01:45:40

问题


I am not able to get anitialiazed lines when doing freehand drawing in javafx canvas. Following is the code ...

import javafx.application.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.canvas.*;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.shape.*;
import javafx.stage.*;

public class Test2 extends Application {
  GraphicsContext gc;

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

  private class MouseDragged implements EventHandler<MouseEvent> {
      public void handle( MouseEvent e ) {
        gc.lineTo( e.getX(), e.getY() );
        gc.stroke();
      }
  }

  private class MousePressed implements EventHandler<MouseEvent> {
      public void handle( MouseEvent e ) {
        gc.moveTo( e.getX(), e.getY() );
      }
  }

  @Override
  public void start(Stage stage) {
    Canvas canvas = new Canvas(500, 500);
    canvas.setOnMouseDragged( new MouseDragged() );
    canvas.setOnMousePressed( new MousePressed() );

    gc = canvas.getGraphicsContext2D();
    gc.setLineCap( StrokeLineCap.ROUND );
    gc.setLineJoin( StrokeLineJoin.ROUND );
    gc.setLineWidth( 0.1 );

    Group root = new Group(canvas);
    Scene scene = new Scene(root);
    stage.setTitle("Test2");
    stage.setScene(scene);
    stage.show();
  }
}

While if I create a swing app I can provide rendering hints to smoothen it out ...

g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );

How do I provide rendering hits to the graphics context in canvas?


回答1:


Try adding this effect to your GraphicsContext:

BoxBlur blur = new BoxBlur();
blur.setWidth(1);
blur.setHeight(1);
blur.setIterations(1);
gc.setEffect(blur);

So (as an example) your start method would now look like this:

  @Override
  public void start(Stage stage) {
    Canvas canvas = new Canvas(500, 500);
    canvas.setOnMouseDragged( new MouseDragged() );
    canvas.setOnMousePressed( new MousePressed() );

    gc = canvas.getGraphicsContext2D();
    gc.setLineCap( StrokeLineCap.ROUND );
    gc.setLineJoin( StrokeLineJoin.ROUND );
    gc.setLineWidth( 1 );

    BoxBlur blur = new BoxBlur();
    blur.setWidth(1);
    blur.setHeight(1);
    blur.setIterations(1);
    gc.setEffect(blur);

    Group root = new Group(canvas);
    Scene scene = new Scene(root);
    stage.setTitle("Test2");
    stage.setScene(scene);
    stage.show();
  }

It's not exactly perfect... but the best thing I've found so far.



来源:https://stackoverflow.com/questions/16816558/canvas-does-not-draw-smooth-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!