Create TexturePaint from BufferedImage in Java

Description

The following code shows how to create TexturePaint from BufferedImage.

Example


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;
// w w  w . j  av  a 2s . co  m
import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2D = (Graphics2D) g;
    int w = getSize().width;
    int h = getSize().height;

    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.fillOval(0, 0, 5, 5);
    Rectangle r = new Rectangle(0, 0, 5, 5);
    TexturePaint tp = new TexturePaint(bi, r);
    g2D.setPaint(tp);
    g2D.drawString("Graphics", 30, 100);

  }
}

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 TexturePaint from BufferedImage in Java




















Home »
  Java Tutorial »
    Graphics »




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