Fills a Shape with the specified Paint object. - Java 2D Graphics

Java examples for 2D Graphics:Shape

Description

Fills a Shape with the specified Paint object.

Demo Code


//package com.java2s;

import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;

import java.awt.geom.AffineTransform;

import java.awt.geom.Rectangle2D;

public class Main {
    /**//w  w w.  ja  v a  2 s.co  m
     * Fills a Shape with the specified Paint object.
     *
     * @param graphics    Graphics to be painted into.
     * @param shape       Shape to be filled.
     * @param paint       Paint to be used.
     * @param paintBounds Optional bounds describing the painted area.
     */
    public static void fillPaintedShape(Graphics2D graphics, Shape shape,
            Paint paint, Rectangle2D paintBounds) {
        if (shape == null) {
            return;
        }
        if (paintBounds == null) {
            paintBounds = shape.getBounds2D();
        }
        AffineTransform txOrig = graphics.getTransform();
        graphics.translate(paintBounds.getX(), paintBounds.getY());
        graphics.scale(paintBounds.getWidth(), paintBounds.getHeight());
        Paint paintOld = null;
        if (paint != null) {
            paintOld = graphics.getPaint();
            graphics.setPaint(paint);
        }
        AffineTransform tx = AffineTransform
                .getScaleInstance(1.0 / paintBounds.getWidth(),
                        1.0 / paintBounds.getHeight());
        tx.translate(-paintBounds.getX(), -paintBounds.getY());
        graphics.fill(tx.createTransformedShape(shape));
        if (paintOld != null) {
            graphics.setPaint(paintOld);
        }
        graphics.setTransform(txOrig);
    }
}

Related Tutorials