JavaFx create HatchStyles (something like of C# .Net)

浪子不回头ぞ 提交于 2019-12-02 17:04:11

问题


Is there anything similar to .Net HatchStyles for filling shapes when using scene shape objects or drawing on JavaFx Canvas (in jdk, third party libraries, sample codes, etc)?

The only solution I currently can think of is using an ImagePattern created via Image screenshots of those .net hatchstyles!

GraphicsContext gc = canvas.getGraphicsContext2D();
ImagePattern pattern = new ImagePattern(new Image("dotnet-pattern.png");
gc.setFill(pattern);

graphical representation of .Net hatch styles:


回答1:


One approach would be a slight modification of what you suggested: use an ImagePattern, but snapshot an appropriate node for the underlying image.

Without actually knowing what the HatchStyles look like, variations on the following might work:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Line;
import javafx.scene.shape.StrokeLineCap;
import javafx.stage.Stage;

public class HatchStyleCanvas extends Application {

    @Override
    public void start(Stage primaryStage) {
        Image hatch = createHatch();
        ImagePattern pattern = new ImagePattern(hatch, 0, 0, 20, 20, false);        
        Canvas canvas = new Canvas(600, 600);
        GraphicsContext gc = canvas.getGraphicsContext2D();
        gc.setFill(pattern);
        gc.fillRect(0, 0, 600, 600);
        primaryStage.setScene(new Scene(new StackPane(canvas)));
        primaryStage.show();
    }

    private Image createHatch() {
        Pane pane = new Pane();
        pane.setPrefSize(20, 20);
        Line fw = new Line(-5, -5, 25, 25);
        Line bw = new Line(-5, 25, 25, -5);
        fw.setStroke(Color.ALICEBLUE);
        bw.setStroke(Color.ALICEBLUE);
        fw.setStrokeWidth(5);
        bw.setStrokeWidth(5);
        pane.getChildren().addAll(fw, bw);
        new Scene(pane);
        return pane.snapshot(null, null);
    }

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

This results in



来源:https://stackoverflow.com/questions/39297719/javafx-create-hatchstyles-something-like-of-c-sharp-net

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