Create Gradient Image in Java

Description

The following code shows how to create Gradient Image.

Example


import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
//from   w w  w.j a v a  2 s .c  o m
import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D)g;

    g2d.drawImage(createGradientImage(200, 200, Color.RED,Color.BLACK),10,10,this);

  }
  public static BufferedImage createGradientImage(int width, int height, Color gradient1,
      Color gradient2) {

    BufferedImage gradientImage = createCompatibleImage(width, height);
    GradientPaint gradient = new GradientPaint(0, 0, gradient1, 0, height, gradient2, false);
    Graphics2D g2 = (Graphics2D) gradientImage.getGraphics();
    g2.setPaint(gradient);
    g2.fillRect(0, 0, width, height);
    g2.dispose();

    return gradientImage;
  }

  private static BufferedImage createCompatibleImage(int width, int height) {

    return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
        .getDefaultConfiguration().createCompatibleImage(width, height);

  }

}

public class Main {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 450, 450);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}

The code above generates the following result.

Create Gradient Image in Java




















Home »
  Java Tutorial »
    Graphics »




Animation
BufferedImage
Color
Font
Gradient
Graphics Settings
Image
Mouse Draw
Print
Shape
Text
Transform