Blend modes in Java2D and JavaFX

As mentioned previously the PDF format contains blend modes, a set of functions determining how overlapping objects on a page interact with the objects underneath it. In this article, I’ll take a look at implementing blending modes in JavaFX (spoiler; it’s very easy).

First of all let’s take a look into how blend modes can be applied in Java2D. Unfortunately, there isn’t out of the box support for the blend modes used in the PDF specification, so we have to do it ourselves. Luckily what we do have is the ability to implement them via the Composite/CompositeContext interfaces. The Composite gets passed to the Graphics2D object using the setComposite(~) method. The CompositeContext is used within the Composite and is the returned variable when createContext(~) is called.

Inside of CompositeContext, the method compose(~) is where the blending happens. compose() passes in three rasters; the first source image, the second source image and the WritableRaster which is where the output goes. With the first two rasters, you can loop through and find the pixel ARGB value for each pixel. For an example of blend modes using this method, check out Romain Guy’s excellent example of implemented blend modes.

multswing

Multply blends inside of our Swing viewer

Now let’s look at how JavaFX approaches blend modes. In FX you can pass a blend mode straight to a Node using setBlendMode(~) and passing in the specified BlendMode enum. Best of all, all the blend modes specified in the PDF specification are all in JavaFX by default (as well as Blend Modes you would expect from Photoshop and the like)! I’ve set up an example project to demonstrate the built in JavaFX on my GitHub account.

multfx

Blends applied using the .setBlendMode(BlendMode blend) method

Abstractions like these are one of the things I really like about JavaFX, being able to simply declare which type of blend mode I want to use and letting the API do the rest of the work makes things much simpler.

This post is part of our “Java Articles Index“ series. In these articles, we aim to explore the world of Java and Javafx. Have a look through!

If you’re a first-time reader, or simply want to be notified when we post new articles and updates, you can keep up to date by social media (TwitterFacebook and Google+) or the Blog RSS.

Related Posts:

The following two tabs change content below.
Simon Lissack is a developer at IDR Solutions, working on JavaFX, Android and the Cloud Conversion service.
Simon

About Simon Lissack

Simon Lissack is a developer at IDR Solutions, working on JavaFX, Android and the Cloud Conversion service.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>