Accueil > Java > Paint a linear gradient

Paint a linear gradient

28/01/2009

/*
 *
 */
public void paint(Graphics g, Color c1, Color c2) {
        Graphics2D g2 = (Graphics2D)g;
        Paint oldPainter = g2.getPaint();
        g2.setPaint(new GradientPaint(new Point2D.Double(0, 0), c1, new Point2D.Double(getWidth(), 0), c2));
        g2.fillRect(0, 0, getWidth(), getHeight());
        g2.setPaint(oldPainter);
}

/*
 * Without gradiant paint
 */
public void paint(Graphics g, Color c1, Color c2) {
    // Add gradient (This might be done before !!)
    Graphics2D g2 = (Graphics2D)g;
    for (int i = -1; i <= this.getWidth(); ++i) {
      float ratio = (float)i / (float)this.getWidth();
      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(1 + i, 0, this.getWidth(), this.getHeight());
      g2.setPaint(c);
      g2.fill(r);
    }
    // Paint using super methods
    super.paint(g);
}

Java

Les commentaires sont fermés.