Creates a clipped image from the given shape. - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Create

Description

Creates a clipped image from the given shape.

Demo Code


//package com.java2s;
import java.awt.*;

import java.awt.image.*;

public class Main {
    /**//  w  w w  .ja v a 2 s .  co  m
     * Creates a clipped image from the given <tt>shape</tt>.
     * @param shape the shape from which to create the image
     * @param g the <tt>Graphics</tt> object giving access to the graphics
     * device configuration
     * @return the created <tt>BufferedImage</tt>
     */
    public static BufferedImage createClipImage(Graphics2D g, Shape shape) {
        // Create a translucent intermediate image in which we can perform
        // the soft clipping
        GraphicsConfiguration gc = g.getDeviceConfiguration();
        BufferedImage img = gc.createCompatibleImage(
                shape.getBounds().width, shape.getBounds().height,
                Transparency.TRANSLUCENT);
        Graphics2D g2 = img.createGraphics();

        // Clear the image so all pixels have zero alpha
        g2.setComposite(AlphaComposite.Clear);
        g2.fillRect(0, 0, shape.getBounds().width, shape.getBounds().height);

        // Render our clip shape into the image.  Note that we enable
        // antialiasing to achieve the soft clipping effect.  Try
        // commenting out the line that enables antialiasing, and
        // you will see that you end up with the usual hard clipping.
        g2.setComposite(AlphaComposite.Src);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.WHITE);
        g2.fill(shape);
        g2.dispose();

        return img;
    }
}

Related Tutorials