Java/2D Graphics GUI/Gradient Paint

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A cyclic gradient

   
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    new BasicDraw();
  }
  BasicDraw() {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Color startColor = Color.red;
    Color endColor = Color.blue;
    int startX = 10, startY = 20, endX = 30, endY = 40;
    GradientPaint gradient = new GradientPaint(startX, startY, startColor, endX, endY, endColor,true);
    g2d.setPaint(gradient);
    g2d.draw(new Rectangle(20, 20, 200, 200));
  }
}



A non-cyclic gradient

   
 
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    new BasicDraw();
  }
  BasicDraw() {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Color startColor = Color.red;
    Color endColor = Color.blue;
    int startX = 10, startY = 20, endX = 30, endY = 40;
    
    GradientPaint gradient = new GradientPaint(startX, startY, startColor, endX, endY, endColor);
    g2d.setPaint(gradient);
    g2d.draw(new Rectangle(20,20,200,200));
  }
}



Another GradientPaint Demo

   
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GradientPaintDemo extends JPanel {
  public void init() {
    setBackground(Color.white);
  }
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setPaint(new GradientPaint(0, 0, Color.lightGray, 200,
        200, Color.blue, false));
  
    Rectangle r = new Rectangle(5,5,200,200);
    
    g2.fill(r);
  }
  public static void main(String s[]) {
    JFrame f = new JFrame();
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    GradientPaintDemo p = new GradientPaintDemo();
    f.getContentPane().add("Center", p);
    p.init();
    f.pack();
    f.setSize(new Dimension(250, 250));
    f.show();
  }
}



Color gradient

   
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ColorBlocks extends JPanel{
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        Dimension d = getSize();
        g2.translate(d.width / 2, d.height / 2);
            
        Color[] colors = {
            Color.white, Color.lightGray, Color.gray, Color.darkGray,
            Color.black, Color.red, Color.pink, Color.orange,
            Color.yellow, Color.green, Color.magenta, Color.cyan, Color.blue
        };
            
        float size = 25;
        float x = -size * colors.length / 2;
        float y = -size * 3 / 2;
            
        // Show all the predefined colors.
        for (int i = 0; i < colors.length; i++) {
          Rectangle2D r = new Rectangle2D.Float(
              x + size * (float)i, y, size, size);
          g2.setPaint(colors[i]);
          g2.fill(r);
        }
            
        //a linear gradient.
        y += size;
        Color c1 = Color.yellow;
        Color c2 = Color.blue;
        for (int i = 0; i < colors.length; i++) {
          float ratio = (float)i / (float)colors.length;
          int red = (int)(c2.getRed() * ratio + c1.getRed() * (1 - ratio));
          int green = (int)(c2.getGreen() * ratio +
                            c1.getGreen() * (1 - ratio));
          int blue = (int)(c2.getBlue() * ratio +
                           c1.getBlue() * (1 - ratio));
          Color c = new Color(red, green, blue);
          Rectangle2D r = new Rectangle2D.Float(
              x + size * (float)i, y, size, size);
          g2.setPaint(c);
          g2.fill(r);
        }
            
        // Show an alpha gradient.
        y += size;
        c1 = Color.red;
        for (int i = 0; i < colors.length; i++) {
          int alpha = (int)(255 * (float)i / (float)colors.length);
          Color c = new Color(c1.getRed(), c1.getGreen(),
                              c1.getBlue(), alpha);
          Rectangle2D r = new Rectangle2D.Float(
              x + size * (float)i, y, size, size);
          g2.setPaint(c);
          g2.fill(r);
        }
            
        // Draw a frame around the whole thing.
        y -= size * 2;
        Rectangle2D frame = new Rectangle2D.Float(x, y, size * colors.length, size * 3);
        g2.setPaint(Color.black);
        g2.draw(frame);
      }
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.getContentPane().add(new ColorBlocks());
    f.setSize(350, 250);
    f.show();
  }
}



Control the direction of Gradients

   
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GradientsDirection extends JPanel {
  public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    GradientPaint gp1 = new GradientPaint(5, 25, Color.yellow, 20, 2, Color.black, true);
    g2d.setPaint(gp1);
    g2d.fillRect(20, 80, 300, 40);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("GradientsDirection");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new GradientsDirection());
    frame.setSize(350, 350);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}



Drawing with a Gradient Color

   
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BasicDraw {
  public static void main(String[] args) {
    new BasicDraw();
  }
  BasicDraw() {
    JFrame frame = new JFrame();
    frame.add(new MyComponent());
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}
class MyComponent extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Color startColor = Color.red;
    Color endColor = Color.blue;
    int startX = 10, startY = 20, endX = 30, endY = 40;
    
    GradientPaint gradient = new GradientPaint(startX, startY, startColor, endX, endY, endColor);
    g2d.setPaint(gradient);
    g2d.draw(new Rectangle(20,20,200,200));
  }
}



GradientPaint demo

   
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class GradientPaintDemo2D extends JApplet {
  public void init() {
    setBackground(Color.white);
    setForeground(Color.white);
  }
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setPaint(Color.gray);
    int x = 5;
    int y = 7;
    // fill RoundRectangle2D.Double
    GradientPaint redtowhite = new GradientPaint(x, y, Color.red, 200, y,
        Color.blue);
    g2.setPaint(redtowhite);
    g2.fill(new RoundRectangle2D.Double(x, y, 200, 200, 10, 10));
    g2.setPaint(Color.black);
    g2.drawString("Filled RoundRectangle2D", x, 250);
  }
  public static void main(String s[]) {
    JFrame f = new JFrame("");
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    JApplet applet = new GradientPaintDemo2D();
    f.getContentPane().add("Center", applet);
    applet.init();
    f.pack();
    f.setSize(new Dimension(300, 300));
    f.show();
  }
}



GradientPaint Ellipse

   
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class GradientPaintEllipse extends JApplet {
  public void init() {
    setBackground(Color.white);
    setForeground(Color.white);
  }
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    int x = 5;
    int y = 7;
    // fill Ellipse2D.Double
    GradientPaint redtowhite = new GradientPaint(x, y, Color.red, 200, y, Color.white);
    g2.setPaint(redtowhite);
    g2.fill(new Ellipse2D.Double(x, y, 200, 200));
    g2.setPaint(Color.black);
    g2.drawString("Filled Ellipse2D", x,250);
  }
  public static void main(String s[]) {
    JFrame f = new JFrame("");
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
    JApplet applet = new GradientPaintEllipse();
    f.getContentPane().add("Center", applet);
    applet.init();
    f.pack();
    f.setSize(new Dimension(300, 300));
    f.show();
  }
}



GradientPaint: iron

   
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SimplestGradientPaint extends JPanel{
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.getContentPane().add(new SimplestGradientPaint());
    f.setSize(350, 250);
    f.show();
  }
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    Ellipse2D e = new Ellipse2D.Float(40, 40, 120, 120);
    GradientPaint gp = new GradientPaint(75, 75, Color.white, 95, 95,
        Color.gray, true);
    g2.setPaint(gp);
    g2.fill(e);
  }
}



Gradients: a smooth blending of shades from light to dark or from one color to another

   
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GradientsRedYellow extends JPanel {
  public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    GradientPaint gp1 = new GradientPaint(5, 5, Color.red, 20, 20, Color.yellow, true);
    g2d.setPaint(gp1);
    g2d.fillRect(20, 20, 300, 40);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("GradientsRedYellow");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new GradientsRedYellow());
    frame.setSize(350, 350);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}



Gradient Shapes

   
 

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RadialGradientPaint;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/*
 * DrawShapes_2008.java
 *
 * Created on May 1, 2007, 4:16 PM
 *
 * Copyright (c) 2007, Sun Microsystems, Inc
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the TimingFramework project nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 *
 * @author Chet
 */
public class DrawShapes_2008 extends JComponent {
    private List<Shape> shapes = new ArrayList();
    private boolean getStar = true;
    
    /**
     * Generates a star Shape from the given location, radii, and points
     * parameters. The Shape is created by constructing a GeneralPath
     * that moves between the inner and outer rings.
     */
    private static Shape generateStar(double x, double y,
                                      double innerRadius, double outerRadius,
                                      int pointsCount) {
        GeneralPath path = new GeneralPath();
        double outerAngleIncrement = 2 * Math.PI / pointsCount;
        double outerAngle = 0.0;
        double innerAngle = outerAngleIncrement / 2.0;
        x += outerRadius;
        y += outerRadius;
        float x1 = (float) (Math.cos(outerAngle) * outerRadius + x);
        float y1 = (float) (Math.sin(outerAngle) * outerRadius + y);
        float x2 = (float) (Math.cos(innerAngle) * innerRadius + x);
        float y2 = (float) (Math.sin(innerAngle) * innerRadius + y);
        path.moveTo(x1, y1);
        path.lineTo(x2, y2);
        outerAngle += outerAngleIncrement;
        innerAngle += outerAngleIncrement;
        for (int i = 1; i < pointsCount; i++) {
            x1 = (float) (Math.cos(outerAngle) * outerRadius + x);
            y1 = (float) (Math.sin(outerAngle) * outerRadius + y);
            path.lineTo(x1, y1);
            x2 = (float) (Math.cos(innerAngle) * innerRadius + x);
            y2 = (float) (Math.sin(innerAngle) * innerRadius + y);
            path.lineTo(x2, y2);
            outerAngle += outerAngleIncrement;
            innerAngle += outerAngleIncrement;
        }
        path.closePath();
        return path;
    }
    
    /**
     * Generates a donut shape from the given location and radii by subtracting
     * an inner circular Area from an outer one.
     */
    private static Shape generateDonut(double x, double y,
            double innerRadius, double outerRadius) {
        Area a1 = new Area(new Ellipse2D.Double(x, y, outerRadius, outerRadius));
        double innerOffset = (outerRadius - innerRadius)/2;
        Area a2 = new Area(new Ellipse2D.Double(x + innerOffset, y + innerOffset, 
                innerRadius, innerRadius));
        a1.subtract(a2);
        return a1;
    }
    /** 
     * This class processes mouse clicks and generates stars and donuts,
     * alternately, in the click location. The new shape is added to the
     * List of current shapes, then the scene is repainted.
     */
    private class ClickReceiver extends MouseAdapter {
        public void mouseClicked(MouseEvent me) {
            int centerX = me.getX();
            int centerY = me.getY();
            double innerSize = 1 + (25 * Math.random());
            double outerSize = innerSize + 10 + (15 * Math.random());
            Shape newShape;
            if (getStar) {
                int numPoints = (int)(8 * Math.random() + 5);
                newShape = generateStar(centerX - outerSize, 
                        centerY - outerSize,
                        innerSize, outerSize, numPoints);
            } else {
                newShape = generateDonut(centerX - outerSize/2, 
                        centerY - outerSize/2,
                        innerSize, outerSize);
            }
            getStar = !getStar;
            shapes.add(newShape);
            repaint();
        }
    }
    
    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        // Paint a gradient for the sky
        GradientPaint background = new GradientPaint(0f, 0f, Color.GRAY.darker(),
                0f, (float)getHeight(), Color.GRAY.brighter());
        g2d.setPaint(background);
        g2d.fillRect(0, 0, getWidth(), 4*getHeight()/5);
        
        // Paint a gradient for the ground
        background = new GradientPaint(0f, (float)4*getHeight()/5, 
                Color.BLACK,
                0f, (float)getHeight(), Color.GRAY.darker());
        g2d.setPaint(background);
        g2d.fillRect(0, 4*getHeight()/5, getWidth(), getHeight()/5);
        
        // Enable anti-aliasing to get smooth outlines
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        
        // Iterate through all of the current shapes
        for (Shape shape : shapes) {
            // Get the bounds to compute the RadialGradient properties
            Rectangle rect = shape.getBounds();
            Point2D center = new Point2D.Float(
                    rect.x + (float)rect.width / 2.0f,
                    rect.y + (float)rect.height / 2.0f);
            float radius = (float)rect.width / 2.0f;
            float[] dist = {0.1f, 0.9f};
            Color[] colors = {Color.WHITE, Color.BLACK};
            
            // Create and set a RadialGradient centered on the object,
            // going from white at the center to black at the edges
            RadialGradientPaint paint = new RadialGradientPaint(center, radius,
                    dist, colors);
            g2d.setPaint(paint);
            
            // Finally, render our shape
            g2d.fill(shape);
        }
    }
    
    /**
     * Creates a new instance of DrawShapes_2008
     */
    public DrawShapes_2008() {
        setBackground(Color.WHITE);
        addMouseListener(new ClickReceiver());
    }
    
    private static void createAndShowGUI() {    
        JFrame f = new JFrame("Draw Shapes");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(500, 500);
        f.add(new DrawShapes_2008());
        f.setVisible(true);
    }
    
    public static void main(String args[]) {
        Runnable doCreateAndShowGUI = new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        };
        SwingUtilities.invokeLater(doCreateAndShowGUI);
    }
}



Gradients in the middle

   
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GradientsMiddle extends JPanel {
  public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    GradientPaint gp1 = new GradientPaint(0, 0, Color.orange, 0, 20, Color.black, true);
    g2d.setPaint(gp1);
    g2d.fillRect(20, 260, 300, 40);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("GradientsMiddle");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new GradientsMiddle());
    frame.setSize(350, 350);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}



Horizontal Gradients

   
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GradientsLine extends JPanel {
  public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    GradientPaint gp1 = new GradientPaint(5, 25, Color.green, 2, 2, Color.black, true);
    g2d.setPaint(gp1);
    g2d.fillRect(20, 140, 300, 40);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("GradientsLine");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new GradientsLine());
    frame.setSize(350, 350);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}



Returns true if the two Paint objects are equal OR both null.

  
import java.awt.GradientPaint;
import java.awt.Paint;
/* 
 * JCommon : a free general purpose class library for the Java(tm) platform
 * 
 *
 * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
 * 
 * Project Info:  http://www.jfree.org/jcommon/index.html
 *
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License as published by 
 * the Free Software Foundation; either version 2.1 of the License, or 
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 
 * USA.  
 *
 * [Java is a trademark or registered trademark of Sun Microsystems, Inc. 
 * in the United States and other countries.]
 * 
 * -------------------
 * PaintUtilities.java
 * -------------------
 * (C) Copyright 2003-2005, by Object Refinery Limited.
 *
 * Original Author:  David Gilbert (for Object Refinery Limited);
 * Contributor(s):   -;
 *
 * $Id: PaintUtilities.java,v 1.10 2007/11/02 17:50:37 taqua Exp $
 *
 * Changes
 * -------
 * 13-Nov-2003 : Version 1 (DG);
 * 04-Oct-2004 : Renamed PaintUtils --> PaintUtilities (DG);
 * 23-Feb-2005 : Rewrote equal() method with less indenting required (DG);
 *
 */
public class Main {
  /**
   * Returns <code>true</code> if the two <code>Paint</code> objects are equal 
   * OR both <code>null</code>.  This method handles
   * <code>GradientPaint</code> as a special case.
   *
   * @param p1  paint 1 (<code>null</code> permitted).
   * @param p2  paint 2 (<code>null</code> permitted).
   *
   * @return A boolean.
   */
  public static boolean equal(final Paint p1, final Paint p2) {
      // handle cases where either or both arguments are null
      if (p1 == null) {
          return (p2 == null);   
      }
      if (p2 == null) {
          return false;   
      }
      
      boolean result = false;
      // handle GradientPaint as a special case...
      if (p1 instanceof GradientPaint && p2 instanceof GradientPaint) {
          final GradientPaint gp1 = (GradientPaint) p1;
          final GradientPaint gp2 = (GradientPaint) p2;
          result = gp1.getColor1().equals(gp2.getColor1()) 
              && gp1.getColor2().equals(gp2.getColor2())
              && gp1.getPoint1().equals(gp2.getPoint1())    
              && gp1.getPoint2().equals(gp2.getPoint2())
              && gp1.isCyclic() == gp2.isCyclic()
              && gp1.getTransparency() == gp1.getTransparency(); 
      }
      else {
          result = p1.equals(p2);
      }
      return result;
  }
}



Round GradientPaint Fill demo

   
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.PaintContext;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.ColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RoundGradientPaintFill extends JPanel{
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    RoundRectangle2D r = new RoundRectangle2D.Float(5, 5, 150, 150, 25,
        25);
    RoundGradientPaint rgp = new RoundGradientPaint(75, 75, Color.magenta,
        new Point2D.Double(0, 85), Color.blue);
    g2.setPaint(rgp);
    g2.fill(r);
  }
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.getContentPane().add(new RoundGradientPaintFill());
    f.setSize(200, 200);
    f.show();
  }

  class RoundGradientPaint implements Paint {
    protected Point2D point;
    protected Point2D mRadius;
    protected Color mPointColor, mBackgroundColor;
    public RoundGradientPaint(double x, double y, Color pointColor,
        Point2D radius, Color backgroundColor) {
      if (radius.distance(0, 0) <= 0)
        throw new IllegalArgumentException("Radius must be greater than 0.");
      point = new Point2D.Double(x, y);
      mPointColor = pointColor;
      mRadius = radius;
      mBackgroundColor = backgroundColor;
    }
    public PaintContext createContext(ColorModel cm, Rectangle deviceBounds,
        Rectangle2D userBounds, AffineTransform xform, RenderingHints hints) {
      Point2D transformedPoint = xform.transform(point, null);
      Point2D transformedRadius = xform.deltaTransform(mRadius, null);
      return new RoundGradientContext(transformedPoint, mPointColor,
          transformedRadius, mBackgroundColor);
    }
    public int getTransparency() {
      int a1 = mPointColor.getAlpha();
      int a2 = mBackgroundColor.getAlpha();
      return (((a1 & a2) == 0xff) ? OPAQUE : TRANSLUCENT);
    }
  }
  public class RoundGradientContext implements PaintContext {
    protected Point2D mPoint;
    protected Point2D mRadius;
    protected Color color1, color2;
    public RoundGradientContext(Point2D p, Color c1, Point2D r, Color c2) {
      mPoint = p;
      color1 = c1;
      mRadius = r;
      color2 = c2;
    }
    public void dispose() {
    }
    public ColorModel getColorModel() {
      return ColorModel.getRGBdefault();
    }
    public Raster getRaster(int x, int y, int w, int h) {
      WritableRaster raster = getColorModel().createCompatibleWritableRaster(
          w, h);
      int[] data = new int[w * h * 4];
      for (int j = 0; j < h; j++) {
        for (int i = 0; i < w; i++) {
          double distance = mPoint.distance(x + i, y + j);
          double radius = mRadius.distance(0, 0);
          double ratio = distance / radius;
          if (ratio > 1.0)
            ratio = 1.0;
          int base = (j * w + i) * 4;
          data[base + 0] = (int) (color1.getRed() + ratio
              * (color2.getRed() - color1.getRed()));
          data[base + 1] = (int) (color1.getGreen() + ratio
              * (color2.getGreen() - color1.getGreen()));
          data[base + 2] = (int) (color1.getBlue() + ratio
              * (color2.getBlue() - color1.getBlue()));
          data[base + 3] = (int) (color1.getAlpha() + ratio
              * (color2.getAlpha() - color1.getAlpha()));
        }
      }
      raster.setPixels(0, 0, w, h, data);
      return raster;
    }
  }
  
}



Text effect: image texture

   
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TexturedText extends JPanel {
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    Font font = new Font("Times New Roman", Font.PLAIN, 72);
    g2.setFont(font);
    String s = "Java Source and Support";
    Dimension d = getSize();
    float x = 20, y = 100;
    BufferedImage bi = getTextureImage();
    Rectangle r = new Rectangle(0, 0, bi.getWidth(), bi.getHeight());
    TexturePaint tp = new TexturePaint(bi, r);
    g2.setPaint(tp);
    g2.drawString(s, x, y);
  }
  private BufferedImage getTextureImage() {
    // Create the test image.
    int size = 8;
    BufferedImage bi = new BufferedImage(size, size,
        BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = bi.createGraphics();
    g2.setPaint(Color.red);
    g2.fillRect(0, 0, size / 2, size / 2);
    g2.setPaint(Color.yellow);
    g2.fillRect(size / 2, 0, size, size / 2);
    g2.setPaint(Color.green);
    g2.fillRect(0, size / 2, size / 2, size);
    g2.setPaint(Color.blue);
    g2.fillRect(size / 2, size / 2, size, size);
    return bi;
  }
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.getContentPane().add(new TexturedText());
    f.setSize(800, 250);
    f.show();
  }
}



Text effect: rotation and transparent

   
import java.awt.AlphaComposite;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TextRendering extends JPanel {
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    Dimension d = getSize();
    AffineTransform ct = AffineTransform.getTranslateInstance(d.width / 2,
        d.height * 3 / 4);
    g2.transform(ct);
    String s = "www.jexp.ru";
    Font f = new Font("Serif", Font.PLAIN, 128);
    g2.setFont(f);
    int count = 6;
    for (int i = 1; i <= count; i++) {
      AffineTransform oldTransform = g2.getTransform();
      float ratio = (float) i / (float) count;
      g2.transform(AffineTransform.getRotateInstance(Math.PI
          * (ratio - 1.0f)));
      float alpha = ((i == count) ? 1.0f : ratio / 3);
      g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
          alpha));
      g2.drawString(s, 0, 0);
      g2.setTransform(oldTransform);
    }
  }
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.getContentPane().add(new TextRendering());
    f.setSize(800, 800);
    f.show();
  }
}



Texture paint

   
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.TexturePaint;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
public class TexturePaintFill extends JPanel {
  private BufferedImage mImage;
  public TexturePaintFill() throws IOException, ImageFormatException {
    // Load the specified JPEG file.
    InputStream in = getClass().getResourceAsStream("largejexpLogo.jpg");
    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
    mImage = decoder.decodeAsBufferedImage();
    in.close();
  }
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    // a round rectangle.
    RoundRectangle2D r = new RoundRectangle2D.Float(25, 35, 150, 150, 25,
        25);
    // a texture rectangle the same size as the texture image.
    Rectangle2D tr = new Rectangle2D.Double(0, 0, mImage.getWidth(), mImage
        .getHeight());
    // the TexturePaint.
    TexturePaint tp = new TexturePaint(mImage, tr);
    // Now fill the round rectangle.
    g2.setPaint(tp);
    g2.fill(r);
  }
  public static void main(String[] args) throws Exception {
    JFrame f = new JFrame();
    f.getContentPane().add(new TexturePaintFill());
    f.setSize(350, 250);
    f.show();
  }
}



Vertical Gradient Paint

   
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GradientsVertical extends JPanel {
  public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    GradientPaint gp1 = new GradientPaint(25, 25, Color.blue, 15, 25, Color.black, true);
    g2d.setPaint(gp1);
    g2d.fillRect(20, 200, 300, 40);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("GradientsVertical");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new GradientsVertical());
    frame.setSize(350, 350);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}