3

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: original picture

With "Inverted Circle" (What I want to draw): with inverted circle

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!

MCMastery
  • 3,099
  • 2
  • 20
  • 43

2 Answers2

1

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);
Jai
  • 8,165
  • 2
  • 21
  • 52
  • I would use this, but unfortunately I am making a game, so I'm using a Canvas – MCMastery Jan 14 '17 at 05:40
  • @MCMastery Fabian's way is probably preferred, but `GraphicsContext` supports [BlendMode](http://docs.oracle.com/javase/8/javafx/api/javafx/scene/canvas/GraphicsContext.html#setGlobalBlendMode-javafx.scene.effect.BlendMode-) as well. If you are out of solution, you can take a look at that. – Jai Jan 16 '17 at 00:43
1

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();
}
fabian
  • 80,457
  • 12
  • 86
  • 114