Here you can find the source of drawCenteredImage(Rectangle2D bounds, Graphics2D g2, Image image, ImageObserver observer, int imageWidth, int imageHeight, boolean shrink)
public static void drawCenteredImage(Rectangle2D bounds, Graphics2D g2, Image image, ImageObserver observer, int imageWidth, int imageHeight, boolean shrink)
//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); }/* ww w . j av a2 s. c om*/ // 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); } } }