我不太确定直接使用 GraphicsContext
,但你可以使用混合来实现。
ImageView image; // Your image
Circle mask = new Circle();
Group g = new Group();
g.setBlendMode(BlendMode.SRC_ATOP);
g.getChildren.add(image);
g.getChildren.add(mask);
@Override
public void start(Stage primaryStage) {
Image image = new Image("https://istack.dev59.com/zEoW1.webp");
double w = image.getWidth();
double h = image.getHeight();
Canvas canvas = new Canvas(w, h);
GraphicsContext gc = canvas.getGraphicsContext2D();
// draw background
gc.setFill(Color.BLACK);
gc.fillRect(0, 0, w, h);
double r = Math.min(h, w) * 2 / 5;
double cx = w / 2;
double cy = h / 2;
// create circular path
gc.beginPath();
gc.moveTo(cx - r, cy); // to first point on the circle
gc.arc(cx, cy, r, r, 180, 360);
gc.closePath();
gc.clip();
gc.drawImage(image, 0, 0);
StackPane root = new StackPane();
root.getChildren().add(canvas);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
GraphicsContext
也支持BlendMode。如果你没有解决方案,可以看一下这个。 - Jai