TexturePaint with BufferedImage : TexturePaint « 2D Graphics « Java Tutorial






TexturePaint with BufferedImage
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class TextureWithBufferedImage extends JFrame {
  public TextureWithBufferedImage() {
    getContentPane().add(new DrawingCanvas());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500, 500);
    setVisible(true);
  }

  public static void main(String arg[]) {
    new TextureWithBufferedImage();
  }
}

class DrawingCanvas extends JPanel {

  DrawingCanvas() {
    setSize(300, 300);
    setBackground(Color.white);

  }

  public void paint(Graphics g) {
    Graphics2D g2D = (Graphics2D) g;
    Rectangle2D rec1, rec2, rec3, rec4, rec5;
    rec1 = new Rectangle2D.Float(25, 25, 75, 150);
    rec2 = new Rectangle2D.Float(125, 25, 10, 75);
    rec3 = new Rectangle2D.Float(75, 125, 125, 75);
    rec4 = new Rectangle2D.Float(25, 15, 12, 75);
    rec5 = new Rectangle2D.Float(15, 50, 15, 15);

    AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
        1);
    g2D.setComposite(ac);

    g2D.setStroke(new BasicStroke(5.0f));
    g2D.draw(rec1);
    GradientPaint gp = new GradientPaint(125f, 25f, Color.yellow, 225f, 100f,
        Color.blue);
    g2D.setPaint(gp);
    g2D.fill(rec2);
    BufferedImage bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
    Graphics2D big = bi.createGraphics();
    big.setColor(Color.magenta);
    big.fillRect(0, 0, 5, 5);
    big.setColor(Color.black);
    big.drawLine(0, 0, 5, 5);
    Rectangle r = new Rectangle(0, 0, 5, 5);
    TexturePaint tp = new TexturePaint(bi, r);

    g2D.setPaint(tp);
    g2D.fill(rec3);
    g2D.setColor(Color.green);
    g2D.fill(rec4);
    g2D.setColor(Color.red);
    g2D.fill(rec5);
  }
}








16.19.TexturePaint
16.19.1.A texture is a bitmap image applied to a shape
16.19.2.TexturePaint with GIF image
16.19.3.TexturePaint with BufferedImageTexturePaint with BufferedImage