Adding BlendMode to Cropped Node in JavaFX

Is there a way to add a BlendMode (or a Blend effect) to a Node that has been trimmed? It seems that if I try to add a clip to Node with BlendMode already installed, BlendMode will be canceled by the clip and will no longer work properly. Sample code to reproduce the problem:

package display.fx.demo;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.effect.BlendMode;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class BlendModeClipProblem extends Application {
    public Rectangle blueRect = new Rectangle(0, 0, 30, 30);
    public Rectangle redRect = new Rectangle(15, 15, 30, 30);

    @Override
    public void start(final Stage stage)
            throws Exception {
        final Pane pane = new Pane();
        final Scene scene = new Scene(pane);
        pane.getChildren().add(blueRect);
        pane.getChildren().add(redRect);

        blueRect.setFill(Color.BLUE);
        redRect.setFill(Color.RED);

        redRect.setBlendMode(BlendMode.ADD);

        // Comment this next line to see blending
        redRect.setClip(new Rectangle(15, 15, 20, 20));

        stage.setScene(scene);
        stage.show();
    }
}
+4
source share
1 answer

Try something like this (use Cached Rectangle)

@Override
    public void start(final Stage stage)
            throws Exception {
        final Pane pane = new Pane();
        final Scene scene = new Scene(pane);
        pane.getChildren().add(blueRect);
        pane.getChildren().add(redRect);

        blueRect.setFill(Color.BLUE);
        redRect.setFill(Color.RED);

        redRect.setBlendMode(BlendMode.ADD);

        redRect.setCache(true);
        redRect.setCacheHint(CacheHint.QUALITY);

        redRect.setClip(new Rectangle(15, 15, 20, 20));

        stage.setScene(scene);
        stage.show();
    }
+2
source

Source: https://habr.com/ru/post/1690650/


All Articles