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.
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.
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!
Are you a Developer working with PDF files?
Our developers guide contains a large number of technical posts to help you understand the PDF file Format.
Do you need to solve any of these problems?
|Display PDF documents in a Web app|
|Use PDF Forms in a web browser|
|Convert PDF Documents to an image|
|Work with PDF Documents in Java|