简体   繁体   中英

JavaFX GraphicsContext Inverted Circle

I've been trying to find a way to do this online, but I haven't been able to find anything.

I want to draw an "inverse circle" with the JavaFX GraphicsContext. These images show what I want.

Original: 原始图片

With "Inverted Circle" (What I want to draw): 倒圆圈

In an image editor I can just erase the circle area in the new layer... I don't see any functions that would do that in GraphicsContext.

I'd need to be able to choose the center point and radius of this "circle".

Thanks!

I am not very sure of directly using GraphicsContext , but you can do it using Blending .

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);

Construct a circular path and use it as clip when drawing the image:

@Override
public void start(Stage primaryStage) {
    Image image = new Image("https://i.stack.imgur.com/zEoW1.jpg");
    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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM