Project

General

Profile

Actions

In this example we'll be creating a simple color gradient using a lot of circles (the recommended way is using java.awt.GradientPaint), and then save the resulting image as a png file.

All the code examples assume you are using the usage template.

Import the classes

import com.dkt.graphics.elements.GCircle;
import com.dkt.graphics.utils.Utils;
import java.awt.Color;

Create the circles

The gradient effect will result from incrementing the value of one of the color coordinates, in this example we'll change the red and blue coordinates simultaneously (of course you are encouraged to experiment with the code), and at the same time decrementing the radius of the circle.

The code for this is quite simple:

final int RADIUS = 125;
for (int i = 0; i < RADIUS; i++) {
    Color color = new Color(i, 0, i);
    GCircle circle = new GCircle(0, 0, RADIUS - i);
    circle.setFillPaint(color);
    circle.setPaint(color);
    circle.setFill(true);
    canvas.add(circle);
}

And the result should be as follows:

Screenshot

Save it to a file

There are several options to save the contents of a Canvas into a file as an image (it can also be saved as text), but the recommended way is with the help of the Utils class included in the com.dkt.graphics.utils package.
There are two basic options with or without background, the main difference being that the later will ignore the background paint and let it transparent.

The code is very simple:

try {
    // This method requires a canvas, the name of the file, and a
    // boolean value which represents whether you want the
    // background or not.
    Utils.saveScreenshot(canvas, "gradient.png", false);
} catch (java.io.IOException ex) {
    System.out.println("Unable to write the file!");
}

Trim the image (alternative approach)

There's an alternative approach for this process which includes trimming the image to an optimum size (that is without all the extra space around the drawing).

There are three steps to achieve this:

Create an image in memory from the canvas

// import BufferedImage from java.awt.image
BufferedImage image = Utils.getImage(canvas, false);

Trim the image

// This method requires the color to omit, if the value
// is null then it will omit r=0 g=0 b=0 a=0 which is
// the background set by Utils.getImage(...)
image = Utils.trimImage(image, null);

Save the image to a file

// import File from java.io
// import ImageIO from javax.imageio
try {
    File file = new File("trimmed_gradient.png");
    ImageIO.write(image, "png", file);
} catch (java.io.IOException ex) {
    System.out.println("Unable to write the file!");
}

Save the image as text

You can checkout GraphicCreator

for2 18 1 255 125 1 0 "
    color  %1$d 0 %1$d;
    colorf %1$d 0 %1$d;
    circle 0 0 %2$d
"

The final code can be downloaded from here -> CircularGradient.java

Updated by Federico Vera almost 3 years ago · 4 revisions

Go to top