draw Centered Image - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Effect

Description

draw Centered Image

Demo Code

/**//from w ww.j a  va 2  s. c om
 * Copyright 1998-2008, CHISEL Group, University of Victoria, Victoria, BC, Canada.
 * All rights reserved.
 */
//package com.java2s;

import java.awt.Graphics2D;
import java.awt.Image;

import java.awt.geom.Rectangle2D;

import java.awt.image.ImageObserver;

public class Main {
    public static void drawCenteredImage(Rectangle2D bounds, Graphics2D g2,
            Image image, ImageObserver observer, int imageWidth,
            int imageHeight, boolean shrink) {
        int x = (int) bounds.getX();
        int y = (int) bounds.getY();
        int w = Math.min(imageWidth, (int) bounds.getWidth());
        int h = Math.min(imageHeight, (int) bounds.getHeight());

        if (shrink
                && ((imageWidth > bounds.getWidth()) || (imageHeight > bounds
                        .getHeight()))) {
            // shrink image to match bounds - keep aspect ratio fixed
            double scaleWidth = bounds.getWidth() / imageWidth;
            double scaleHeight = bounds.getHeight() / imageHeight;
            if (scaleWidth < scaleHeight) {
                w = (int) (scaleWidth * imageWidth);
                h = (int) (scaleWidth * imageHeight);
            } else {
                w = (int) (scaleHeight * imageWidth);
                h = (int) (scaleHeight * imageHeight);
            }
            // scales the image
            g2.drawImage(image, x, y, w, h, /* g2.getColor(),*/observer);
        } else {
            // center the image
            x += (int) Math.max(bounds.getX(), (bounds.getWidth() - w) / 2); // center horizontally
            y += (int) Math
                    .max(bounds.getY(), (bounds.getHeight() - h) / 2); // center vertically
            // chop off the outer rim of the image if necessary
            int srcX = Math.max(0, (imageWidth / 2) - (w / 2));
            int srcY = Math.max(0, (imageHeight / 2) - (h / 2));
            // no scaling is done here - note it uses only (x, y) coordinates, not width and height
            g2.drawImage(image, x, y, x + w, y + h, srcX, srcY, srcX + w,
                    srcY + h, /* g2.getColor(),*/observer);
        }
    }
}

Related Tutorials