Setting the Clipping Area with a Shape - Java 2D Graphics

Java examples for 2D Graphics:Shape

Description

Setting the Clipping Area with a Shape

Demo Code

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;

import javax.swing.JComponent;

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

    // Create an oval shape that's as large as the component
    float fx = 0;
    float fy = 0;
    float fw = getSize().width - 1;
    float fh = getSize().height - 1;
    Shape shape = new java.awt.geom.Ellipse2D.Float(fx, fy, fw, fh);

    // Set the clipping area
    g2d.setClip(shape);/*from w w  w  .j av a 2 s  .  co  m*/

    // Draw an image
    int x = 0;
    int y = 0;
    Image image = null;
    g2d.drawImage(image, x, y, this);
  }
}

Related Tutorials