the matt jones website.‎ > ‎Java‎ > ‎

Gradients with GradientPaint

Graphics can be painted with Patterns, Gradients and solid colours.

How do you control the angle of the gradient?

The gradient angle is defined by the two points set in the Gradient constructor. 

Below is the code of a GradientPaint constructor:
gradient = new GradientPaint(X1, Y1, Colour1, X2, Y2,  Colour2, false);

The path that the gradient takes follows the line between the two points.

For example, the following code produces the below gradient example:
gradient = new GradientPaint(0, 0, Color.LIGHT_GRAY, 0, 200, Color.DARK_GRAY, false);



The next example shows the gradient line following the horizontal plane:
gradient = new GradientPaint(0, 0, Color.LIGHT_GRAY, 0, gradientLength, Color.DARK_GRAY, false);

Applying the Gradient to a Shape/Object

After constructing the gradient as above, use the "setPaint" method then draw the object, for example:

BufferedImage buffRenderImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D flatGraphic = buffRenderImage.createGraphics();
GradientPaint gradient = new GradientPaint(0, 0, Color.LIGHT_GRAY, gradientLength, 0, Color.DARK_GRAY, false);
flatGraphic.setPaint(gradient);
flatGraphic.fillRect(0, 0, 100, 100); 

Useful Sites



Comments